I have some Firebug console function calls that I wanted to disable when Firebug wasn't enabled, e.g. console isn't defined. This works fine in IE6 and FF3, but not in Chrome:
var log; if(console){ log = console.log; }else{ log = function(){ return; } } I get an "Uncaught TypeError: Illegal Invocation" in Chrome =/
I read about the issue here, where you have to apply a context, which is kind of new to me... and I can't seem to figure how to accomplish the above in all browsers...
Yes, you should persist the context :
var log; if (window.console && typeof console.log === "function"){ // use apply to preserve context and invocations with multiple arguments log = function () { console.log.apply(console, arguments); }; } else { log = function(){ return; } } What is happening is that the context (the this value), is implicitly set when you call a function, for example:
var obj = { method: function () { return this; } }; obj.method() === obj; // true In this case, you are calling a function that is defined as a property of an object, when the function is invoked, the this value is set to that object.
Now as in your example, if you copy a reference of that method to a variable:
var method = obj.method; method() === window; // global object As you can see, the this value refers to the global object.
So, to avoid this implicit behavior you can set the context explicitly, with the call or apply functions.
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