Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I rename console.log?

Tags:

javascript

This seems like it should be pretty straightforward:

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

Why doesn't it work?

like image 705
sircodesalot Avatar asked Jun 28 '13 13:06

sircodesalot


1 Answers

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 );
like image 137
Esailija Avatar answered Oct 24 '22 03:10

Esailija