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?
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With