In Javascript, if we are aliasing a function (or, assign a "reference to a function" to another variable), 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 was 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 other methods besides this?