nombreinvicto
nombreinvicto

Reputation: 590

Why is "this" the global / window object in this case?

Relatively new to JavaScript here so any help / explanation would be appreciated.

I have the following toy code example and am struggling to explain to myself why I am getting such an output.

const list = [1, 2];
let newlist = list.map(function (num){
   console.log(this);     // logs the global / window object in the console
   return num * 2;
});

The console.log(this) statement inside the callback function logs the global or the window object in the console. I have gone through this doc for the map() method of the Array prototype and it states that the map() method has a second argument, thisArg. It further say, "If a thisArg parameter is provided to map, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value".

I have not provided any value for the thisArg parameter, so according to the doc, I was expecting the console.log() statement to print out an undefined. So the question is, why is the "this" pointing to the global object in the example code above?

Upvotes: 2

Views: 132

Answers (1)

ibrahim tanyalcin
ibrahim tanyalcin

Reputation: 6491

In the browser, call any anonymous function:

(function(){
    console.log(this === window); //true
}())

So you know that by default, this points to the window object. UNLESS, you pass something else, via calling as a method, from prototype, call, apply etc. Now go look at the map polyfill:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Here the crux is this line:

callback.call(T, kValue, k, O);

Be careful, T is your thisArg if and only if arguments.length > 1, otherwise it is left undefined. And guess what, from MDN Function.prototype.call:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

.call method replaces undefined with global (window):

function.call(thisArg, arg1, arg2, ...)

thisArg

Optional. The value of this provided for the call to a function. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode , null and undefined will be replaced with the global object and primitive values will be converted to objects.

Upvotes: 1

Related Questions