In Javascript, is it true that function aliasing works as long as the function being aliased doesn't

Posted by Jian Lin on Stack Overflow See other posts from Stack Overflow or by Jian Lin
Published on 2010-05-06T06:13:40Z Indexed on 2010/05/06 6:18 UTC
Read the original article Hit count: 266

Filed under:
|
|
|

In Javascript, if we are aliasing a function, such as in:

f = g;
f = obj.display;
obj.f = foo;

all the 3 lines above, they will work as long as the function / method on the right hand side doesn't touch this? Since we are passing in all the arguments, the only way it can mess up is when the function / method on the right uses this?

Actually, line 1 is probably ok if g is also a property of window? If g is referencing obj.display, then the same problem is there.

In line 2, when obj.display touches this, it is to mean the obj, but when f() is invoked, the this is window, so they are different.

In line 3, it is the same: when f() is invoked inside of obj's code, then the this is obj, while foo might be using this to refer to window if it were a property of window. (global function).

So line 2 can be written as

f = function() { obj.display.apply(obj, arguments) }

and line 3:

obj.f = function() { foo.apply(window, arguments) }

Is this the correct method, and are there there other methods besides this?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about binding