通过代理函数将参数传递给console.log作为第一类参数

adi*_*tya 56 javascript

console.log 获取未指定数量的参数并将其内容转储到一行中.

有没有办法可以编写一个函数来传递直接传递给它的参数console.log来维护这种行为?例如:

function log(){
    if(console){
        /* code here */
    }
}
Run Code Online (Sandbox Code Playgroud)

这与以下内容不同:

function log(){
    if(console){
        console.log(arguments);
    }
}
Run Code Online (Sandbox Code Playgroud)

因为arguments是一个数组console.log并将转储该数组的内容.它也不会是:

function log(){
    if(console){
        for(i=0;i<arguments.length;console.log(arguments[i]),i++);
    }
}
Run Code Online (Sandbox Code Playgroud)

因为那将打印不同行中的所有内容.重点是保持console.log行为,但通过代理功能log.

+ ---

我正在寻找一种解决方案,我将来可以应用于所有函数(为函数创建一个代理,保持参数的处理完好无损).如果不能这样做,我会接受一个console.log具体的答案.

Gab*_*oli 85

这应该做..

function log() {
    if(typeof(console) !== 'undefined') {
        console.log.apply(console, arguments);
    }
}
Run Code Online (Sandbox Code Playgroud)

只需添加另一个选项(使用扩展运算符和其余参数 - 尽管arguments可以直接使用传播)

function log(...args) {
    if(typeof(console) !== 'undefined') {
        console.log(...args);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 只是要指出,在你的脚本中使用它仍然会导致IE9或更旧的错误(如果你没有使用`<meta http-equiv ="X-UA-Compatible"content ="IE = edge",甚至IE10也会出错)第一次调用`log();`而不是`if(console)`你应该做`if(typeof(console)!=='undefined')`在你的浏览器中工作和旧的,包括IE6-IE11. (4认同)
  • 这在Chrome/Safari中无效.它抛出了"非法调用"错误. (3认同)
  • @aditya,更新代码..我没有使用正确的上下文..你需要传递`console`作为`this`参数来应用.. (3认同)

nhe*_*ich 8

html5boilerplate代码中有一个很好的例子,它以类似的方式包装console.log,以确保不会破坏任何不能识别它的浏览器.它还添加了历史记录并平滑了console.log实现中的任何差异.

它由Paul Irish开发,他在这里写了一篇文章.

我已粘贴下面的相关代码,这是项目中文件的链接:https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js

// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console) {
    arguments.callee = arguments.callee.caller;
    var newarr = [].slice.call(arguments);
    (typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr));
  }
};

// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,timeStamp,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}}((function(){try {console.log();return window.console;}catch(err){return window.console={};}})());
Run Code Online (Sandbox Code Playgroud)