个性化阅读
专注于IT技术分析

如何覆盖JavaScript中的console方法

点击下载

本文概述

¿为什么要覆盖console方法?

不包括那些仅出于外部原因而来此帖子的人, 我不知道, 你是在互联网上搜索如何覆盖console方法的人!

现在, 很严重的是, 你可能想覆盖console方法, 例如对项目进行更好的错误报告。

如果你正在一个现有项目中工作, 并且想要对失败的东西进行自动错误报告, 而不是创建一个名为ReportError的新方法, 并在每个console.error或console.log之前添加它, 或者删除这些行, 那么它将是最好在某处添加几行并覆盖现有方法(不删除实际操作)。

覆盖console.log

要覆盖console方法, 我们只需要重新定义该方法的执行方式即可。你需要包装代码, 以防止其他功能访问私有(原始)方法。

(function(){
    // Save the original method in a private variable
    var _privateLog = console.log;
    // Redefine console.log method with a custom function
    console.log = function (message) {
        // Here execute something with the given message or arguments variable
        // alert("Our Custom Log Says: " + message);

        /**
          Note: If you want to preserve the same action as the original method does
          then use the following line :
    
          we use apply to invoke the method on console using the original arguments. 
          Simply calling _privateLog(message) would fail because LOG depends on the console
         */
        _privateLog.apply(console, arguments);
    };
})();

注意:前面的代码将完成最后的技巧。你可以使用它来覆盖其他属性。

覆盖其他console方法

以下示例将覆盖所有众所周知的console方法(错误, 警告和信息)。

(function(){
  var _log = console.log;
  var _error = console.error;
  var _warning = console.warning;

  console.error = function(errMessage){
      ImaginarySendMailErrorMethod(errMessage);// Send a mail with the error description
     _error.apply(console, arguments);
  };

  console.log = function(logMessage){
      // Do something with the log message
      _log.apply(console, arguments);
  };

  console.warning = function(warnMessage){
     // do something with the warn message
     _warning.apply(console, arguments);
  };
  
})();

玩得开心 !

赞(0)
未经允许不得转载:srcmini » 如何覆盖JavaScript中的console方法

评论 抢沙发

评论前必须登录!