Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

javascript - Arrow Function in Object Literal


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Note that the Babel translation is assuming strict mode, but your result with window indicates you're running your code in loose mode. If you tell Babel to assume loose mode, its transpilation is different:

var _this = this;                    // **

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

Note the _this global and console.log(_this);, instead of the console.log(undefined); from your strict-mode transpilation.

I'm trying to figure out why an arrow function in an object literal is called with window as this.

Because arrow functions inherit this from the context in which they're created. Apparently, where you're doing this:

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

...this is window. (Which suggests you're not using strict mode; I'd recommend using it where there's no clear reason not to.) If it were something else, such as the undefined of strict mode global code, this within the arrow function would be that other value instead.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...