Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the context of a function in an array?

Tags:

javascript

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.

like image 625
James Allardice Avatar asked Apr 04 '12 09:04

James Allardice


1 Answers

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.

like image 148
Felix Kling Avatar answered Sep 16 '22 14:09

Felix Kling