- Generally speaking,
this
keyword represents an object from each the function has been called from. That is why it is not possible to say for sure which objectthis
is bound to given only the body of the function. - Only the call time defines to which object
this
will be bound. - If there is no parameter supplied for
this
it will be bound to theglobal
object. - Invocation of function with a keyword
new
will result in binding ofthis
to a brand new object:
new object1.fn();
function fn() {
log(this); // {} - irrelevantly to what object1 is.
}
There are several ways to invoke the function by the means of the specific object:
object
.function
() - left-to-the-dot rule - could be used iffunction
is a defined property ofobject
object
['function
']() - same as the abovefunction
.call(binding-for-this
,first-arg
,second-arg
..) - using acall
method on function object. In this way the first parameter that will be passed to invocation will be bound tothis
. Note that in the following examplethis
will be bound toobject2
due to the fact thatcall
overrides method access rules:
object1.function.call(object2, ..)
Problem
Could be seen in the following code snippet:
setTimeout(r.fn, 100)
given the following way of implementing setTimeot
(pseudocode):
function setTimeout(cb, interval) {
wait(interval)
cb()
}
Here the fn
function will be called with this
being bound to global
.
Solution
Pass a completely new function object as a callback:
setTimeout(function() { r.fn() }, 100)