What is the context of the function in the array?

This is what I'm sure I should know the answer, but either I'm just stupid, or somehow I have never come across this before ...

Given the following array declared in the global scope:

var arr = [function() { console.dir(this); }]; 

I would expect this to refer to the Window object. However, when calling the function:

 arr[0]();โ€‹ //Logs Array 

It looks like this actually refers to an array. Then, when I save the reference to the function in another variable and call it, this refers to the Window object:

 var func = arr[0]; func(); //Logs Window 

So why does the function context change? Here's a fiddle demonstrating the above two cases .

+7
source share
4 answers

When you call a function as a property of an object, for example obj.func() , this refers to obj .
This is exactly what you are doing here. arr is your object, and 0 is a property containing the function.

Note: After all, arrays are just objects, and their elements are the values โ€‹โ€‹of their properties (although properties are usually numeric strings (all properties are strings)).

For more details see MDN - this , in this case:

When a function is called as a method of an object, its this set to the object on which the method is called.

In your second case, you call the function "autonomously", so this refers to window . If the code was run in strict mode, this would be undefined .

+5
source

This is because the this keyword is actually an operator that returns a reference to the owner (or owner) of the function in which it was called. Since in the first case the holder is an array (which is an object), it returns an array. In the second case, the holder is a window object.

See this article for more details.

0
source

:

in JavaScript, this always refers to the owner of the function.

You can learn more about this at quirksmode .

0
source

Since the element is a member of the array, and this always points to the owner object (if you are not playing with bind() / call() / apply() , etc.). If you are not part of an object, this will be a global object; which is in the browser environment window . The exception is that you are in strict mode, where this will be undefined .

What you do is actually the same as:

 var ar = { '0' : function () { console.dir(this); } } ar[0](); var func = ar[0]; func(); 

... that might make sense conceptually.

http://jsfiddle.net/TVtwr/1/

0
source

All Articles