Consider the following code:
var obj = {
name: 'Hans',
print: function(p) {
console.log(this.name)
}
};
obj.print(); // prints 'Hans'
We know that print
function is called on object obj
. In other words obj
is (part of) the execution context of the print
. Easy, right?
Now, this is what I'm struggling to comprehend: Consider storing a function reference in an array:
var funcs = [function(p) {
console.log(this.length, this)
}];
funcs[0](); // prints 1 which is the length of the array 'func' and also [ [Function] ]
It means that the execution context of the first element in the array when it's running is the array itself !! My assumption was that what's stored in the array is nothing but a reference to the function, so it's equivalent to this:
var f = function(p) {
console.log(this)
};
var funcs = [f];
f(); // prints Window
which turns out to be wrong. What am I missing here?
The result you're seeing is because arrays are actually objects, and array indexes are properties that happen to have numeric names. When a property contains a function, and you call object.property()
or object["property"]()
, the this
context is the object.
But this only happens when you call the function using property accessor or array index syntax. The association with the object is lost if you assign the function to some other variable and call the function through that. That's why you see the window
object in the last snippet.
You'd see the same effect in the first snippet if you changed obj.print()
to
var foo = obj.print;
foo();