为什么可以't我重命名console.log

Why can't I rename console.log?

本文关键字:重命名 console log 为什么      更新时间:2023-09-26

这似乎应该非常简单:

var print = console.log;
print("something"); // Fails with Invalid Calling Object (IE) / Invalid Invocation (Chrome)

为什么它不起作用?

因为您调用的方法以全局对象为接收器,而该方法严格来说是非泛型的,并且需要Console的一个实例作为接收器。

通用方法的一个例子是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 );