为什么不能重命名console.log? [英] Why can't I rename console.log?
本文介绍了为什么不能重命名console.log?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这似乎应该很简单:
var print = console.log;
print("something"); // Fails with Invalid Calling Object (IE) / Invalid Invocation (Chrome)
为什么不起作用?
推荐答案
如果您使用全局对象作为接收方来调用该方法,而该方法严格地是非泛型的,并且恰好需要 Console的实例
作为接收者.
Becase you are calling the method with the global object as the receiver while the method is strictly non-generic and requires exactly an instance of Console
as the receiver.
通用方法的一个示例是 Array.prototype.push
:
An example of generic method is Array.prototype.push
:
var print = Array.prototype.push;
print(3);
console.log(window[0]) // 3
您可以执行以下操作:
var print = function() {
return console.log.apply( console, arguments );
};
ES5提供了 .bind
,它也实现了与上述相同的功能:
And ES5 provides .bind
that also achieves the same as above:
var print = console.log.bind( console );
这篇关于为什么不能重命名console.log?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文