ES6 arrow function lexical this in V8

北慕城南 提交于 2019-11-27 04:40:59

问题


I have the following ES6 code using a fat arrow function:

var test = {
  firstname: 'David',
  fn: function() {
    return ['one', 'two', 'tree'].map(() => this.firstname)
  }
}
console.log(test.fn())

According to how arrow functions are supposed to work I'd expect this to be the test object. ES6Fiddle, Traceur and Firefox produce the expected output which is ["David", "David", "David"].

When enabling those features in Chrome using chrome://flags/#enable-javascript-harmony, however, I get [undefined, undefined, undefined]. If you console.log(this) it shows that it is the window object and you get an error in strict mode. Is the lexical this for ES6 arrow functions not implemented in V8 yet?


回答1:


Lexical this is the last part of ES6 arrow functions to land in v8 and it is the reason why it is still behind a flag and not ready to ship yet. Adrian Perez at Igalia is implementing arrow functions and the final patch is almost ready to land as soon as a few TurboFan issues are worked out: https://codereview.chromium.org/883823002/




回答2:


The fat arrow is a feature of ES6. It's been introduced in Firefox(Gecko) but not yet in other browsers (and especially not completely in V8 which would be interesting for nodejs/iojs development).Here is a reference doc

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Browser_compatibility

Anyways If you need the scope binding, then instead of => use bind(). Here is a simple example.

Instead of this.

$("#example").on("click", () => {
   // your code goes here
});

Use this.

$("#example").on("click", (function() {
   // your code goes here
}).bind(this));

If you don't need the scope binding then simply do so.

$("#example").on("click", function() {
   console.log("example");
});


来源:https://stackoverflow.com/questions/28029523/es6-arrow-function-lexical-this-in-v8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!