如何将console.log作为参数传递给我的JavaScript函数?

7
在下面的代码中,我可以使用print代替console.log,程序可以正确运行。然而,我想使用console.log,但是我得到了“非法调用”错误。在运行时发生。
function forEach(array, action) {
    for (var i=0; i<array.length; i++) 
        action(array[i]);
}

forEach(["blah", "bac"], console.log);

еҰӮжһңдҪ еҸӘдј йҖ’console并еңЁforEachеҮҪж•°еҶ…и°ғз”ЁlogпјҢе®ғе°ҶжӯЈеёёе·ҘдҪңгҖӮ - Thiago Augustus Oliveira
3个回答

7

通常情况下,在Javascript中无法直接将方法传递给回调函数。在函数调用的时候,this会绑定到一个特定的值,具体取决于你以何种方式进行调用,并且没有像Python一样自动绑定方法的机制。

//does not work.
var obj = {
    x: 17,
    f: function(){ return this.x; }
};

//inside doSomething, f forgets its "this" should be obj
doSomething( obj.f )

在这些情况下,可以使用Function.prototype.bind(或类似于您所选择的库中的函数,因为bind在IE <= 8中不存在)。
//works (for normal methods - see next bit for console.log in particular)
var obj = {
    x: 17,
    f: function(){ return this.x; }
};

doSomething( obj.f.bind(obj) )

然而,对于console.log来说,这通常是不够的。由于它在IE中不是实际的函数(而是一个恶意宿主对象),因此您不能在该浏览器上使用bind、apply和call方法。唯一的解决办法是将调用包装在匿名函数中。

doSomething( function(x){
    return console.log(x);
});

由于在匿名函数中包装console.log很长而且烦人,所以我通常在开发和调试时添加以下全局函数:

function log(message){ return function(x){
    return console.log(message, x);
};};

forEach(['asd', 'zxc'], log('->'));

4
从这里开始:在Chrome中创建console.log()的快捷方式 您可以将console.log替换为console.log.bind(console) 感谢@julian-d的解释:
因为console.log内部会引用this,并期望它是console。如果您“分离”log方法,例如像var log = console.log,则此关联将丢失,并且this将不再指向console(在这种情况下,指向window,如果您在浏览器中)。这就是.bind(obj)的目的:它返回一个方法,在其中this保持固定为obj

但是为什么你不能这样做 log = console.log 呢? - meze
2
由于 console.log 内部会引用 this,并期望它是 console。如果你“分离”了 log 方法,例如像这样:var log = console.log,那么这种关联就会丢失,并且 this 将不再指向 console(在这种情况下将指向 window,如果你在浏览器中)。这就是 .bind(obj) 的目的:它返回一个方法,在内部 this 保持固定为 obj - Julian D.
请记住,bind 并非所有浏览器都支持。请参考 @frm 的答案以查找无需 bind 的解决方案。 - James M
1
这在IE上不起作用(至少旧版本)- console.log不是一个函数,所以缺少bbind呼叫和apply。 - hugomg

3

您可以使用匿名函数作为forEach()console.log()之间的桥梁来解决问题。

forEach(["blah", "bac"], function (element) {
    console.log(element);
});

您的 forEach() 对处理程序保持中立,您不必使用 bind() 来传递对 console.log() 的有效引用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接