In this example why does pushing the function reference onto the array not change the scope
execution context
of this
whereas assigning the function reference to a new variable does change the scope
execution context
of this
?
(function() {
function Car(year) {
this.year = year;
}
Car.prototype = {
logYear: function() {
console.log(this.year);
}
};
var ford = new Car('Ford', 1999);
ford.logYear();
var cbs = [];
cbs.push(ford.logYear);
for(var x = 0; x < cbs.length; x++) {
cbs[x](); // -> 1999 #1
var callback = cbs[x];
callback(); // -> undefined #2
}
})()
Is this because the reference to the function in the array points to the original function on the ford
object where this
is still defined as the instance (#1) and the variable assignment changes the this
to point to the wrapping IIFE
block (#2)?
Is this a good pattern if I need to collect of bunch of methods like this from various objects and call them somewhere else?
How does this referential calling relate to examples like console.error.bind(console)
?
Thanks!
-- Update
Thanks to @Satyajeet for the nice explanation and clarification.
Typos & copying errors aside the reason I was asking this question in the first place is that I suspected what Satyajeet confirmed but an application I am working on does not reflect this behavior (or so I thought).
It turns out that in the application I am performing a similar process to the above code where I call cbs.push(ford.logYear);
, adding multiple methods from different objects to an array.
At a point in the app I call all these methods and expect them to behave in the same way as when they are called in the execution context
scope
of the original object... and they do, because the values the methods interact with are not attached to this
, they are captured in closures.
See example plunker here
-- Update 2
Fixed usage of execution context
and scope
to be accurate for each part of the question/answer.