Javascript 为什么可以';我不能重命名console.log吗?
这似乎应该非常简单:Javascript 为什么可以';我不能重命名console.log吗?,javascript,Javascript,这似乎应该非常简单: var print = console.log; print("something"); // Fails with Invalid Calling Object (IE) / Invalid Invocation (Chrome) 为什么不起作用?因为您调用的方法是以全局对象作为接收器的,而该方法是严格非泛型的,并且只需要一个控制台的实例作为接收器 通用方法的一个示例是Array.prototype.push: var print = Array.prototyp
var print = console.log;
print("something"); // Fails with Invalid Calling Object (IE) / Invalid Invocation (Chrome)
为什么不起作用?因为您调用的方法是以全局对象作为接收器的,而该方法是严格非泛型的,并且只需要一个
控制台的实例作为接收器
通用方法的一个示例是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
,也实现了上述功能:
var print = console.log.bind( console );
另一个解决方案(其中Function.prototype.bind
可用)是var print=console.log.bind(console)代码>请注意,这些解决方案中的任何一个都不能与多个参数一起使用:print('1','2');//“1”