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()
, this
refers to obj
.
This is exactly what you are doing here. arr
is your object and 0
is 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 - this
for more information, in this case:
When a function is called as a method of an object, its
this
is set to the object the method is called on.
In your second case, you call the function "standalone", hence this
refers to window
. If the code was run in strict mode though, this
would be undefined
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With