This is something that I’m sure I should know the answer to, but either I’m just being stupid or I’ve just somehow never come across this before…
Given the following array, declared in the global scope:
var arr = [function() {
console.dir(this);
}];
I would have expected this to refer to the Window object. However, when calling the function:
arr[0](); //Logs Array
It appears that this actually refers to the array. Then, when I store a reference to the function in another variable and call that, this does refer to the Window object:
var func = arr[0];
func(); //Logs Window
So, why does the context of the function change? Here’s a fiddle demonstrating the above two cases.
When you call a function as property of an object, such as
obj.func(),thisrefers toobj.This is exactly what you are doing here.
arris your object and0is the property holding a function.Note: After all, arrays are just objects and their elements are the values of their properties (though properties are typically numerical strings (all properties are strings)).
See MDN –
thisfor more information, in this case:In your second case, you call the function “standalone”, hence
thisrefers towindow. If the code was run in strict mode though,thiswould beundefined.