Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't JavaScript function aliasing work?

Tags:

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...

like image 300
qodeninja Avatar asked Apr 16 '10 15:04

qodeninja


1 Answers

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.

like image 110
Christian C. Salvadó Avatar answered Nov 23 '22 23:11

Christian C. Salvadó