Arrow function in object literal

I am trying to understand why the arrow function in an object literal is called with window like this . Can someone give me some idea?

 var arrowObject = { name: 'arrowObject', printName: () => { console.log(this); } }; // Prints: Window {external: Object, chrome: Object ...} arrowObject.printName(); 

And an object that works as expected:

 var functionObject = { name: 'functionObject', printName: function() { console.log(this); } }; // Prints: Object {name: "functionObject"} functionObject.printName(); 

According to the Babel REPL , they are transmitted to

 var arrowObject = { name: 'arrowObject', printName: function printName() { console.log(undefined); } }; 

and

 var functionObject = { name: 'functionObject', printName: function printName() { console.log(this); } }; 

Why not arrowObject.printName(); called with arrowObject like this ?

Console logs from Fiddle (where use strict; not used).

+6
source share
1 answer

Note that the Babel translation accepts strict mode, but your result with window means that you run your code in free mode. If you tell Babel to accept the free regime, then his transpilation will be different :

 var _this = this; // ** var arrowObject = { name: 'arrowObject', printName: function printName() { console.log(_this); // ** } }; 

Pay attention to _this global and console.log(_this); instead of console.log(undefined); from your strict mode broadcast.

I am trying to figure out why the arrow function in an object literal is called with window like this .

Because arrow functions inherit this from the context in which they are created. Apparently where you do it:

 var arrowObject = { name: 'arrowObject', printName: () => { console.log(this); } }; 

... this is window . (This means that you are not using strict mode, I would recommend using it where there is no clear reason.) If it were something else, for example, an undefined global strict mode code, this function would have a different value within the arrow.

It may be a little clearer that the context where the arrow function is created is if we break your initializer into its logical equivalent:

 var arrowObject = {}; arrowObject.name = 'arrowObject'; arrowObject.printName = () => { console.log(this); }; 
+11
source

All Articles