简体   繁体   English

ES6箭头功能在V8中有词汇

[英]ES6 arrow function lexical this in V8

I have the following ES6 code using a fat arrow function: 我使用胖箭头函数有以下ES6代码:

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. 根据箭头函数应该如何工作,我希望thistest对象。 ES6Fiddle , Traceur and Firefox produce the expected output which is ["David", "David", "David"] . ES6Fiddle ,Traceur和Firefox产生了预期的输出,即["David", "David", "David"]

When enabling those features in Chrome using chrome://flags/#enable-javascript-harmony , however, I get [undefined, undefined, undefined] . 使用chrome://flags/#enable-javascript-harmony在Chrome中启用这些功能时,我得到[undefined, undefined, undefined] If you console.log(this) it shows that it is the window object and you get an error in strict mode. 如果你使用console.log(this)它会显示它是窗口对象,并且在严格模式下会出现错误。 Is the lexical this for ES6 arrow functions not implemented in V8 yet? this ES6箭头功能的词汇是否在V8中没有实现?

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. 词典this是ES6箭头功能的最后一部分落在v8中,这就是为什么它仍然落后于旗帜而尚未准备好发货的原因。 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/ Igalia的Adrian Perez正在实施箭头功能,一旦完成一些TurboFan问题,最终补丁几乎准备就绪: https ://codereview.chromium.org/883823002/

The fat arrow is a feature of ES6. 胖箭是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 它已在Firefox(Gecko)中引入,但尚未在其他浏览器中引入(尤其不完全在V8中,这对于nodejs / iojs开发很有意义。)这是一个参考文档

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Browser_compatibility 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() . 无论如何如果你需要范围绑定,那么而不是=>使用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");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM