Why can't I rename console.log?

后端 未结 1 823
轻奢々
轻奢々 2021-01-01 01:59

This seems like it should be pretty straightforward:

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


        
相关标签:
1条回答
  • 2021-01-01 02:16

    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.

    An example of generic method is Array.prototype.push:

       var print = Array.prototype.push;
       print(3);
       console.log(window[0]) // 3
    

    You can do something like this though:

    var print = function() {
         return console.log.apply( console, arguments );
    };
    

    And ES5 provides .bind that also achieves the same as above:

    var print = console.log.bind( console );
    
    0 讨论(0)
提交回复
热议问题