13

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?

4

2 回答 2

11

Lexicalthis是 ES6 箭头函数在 v8 中的最后一部分,这也是它仍然落后于标志并且尚未准备好发布的原因。Igalia 的 Adrian Perez 正在实现箭头功能,一旦解决了一些 TurboFan 问题,最终补丁几乎已经准备就绪:https ://codereview.chromium.org/883823002/

于 2015-01-28T03:20:32.333 回答
1

粗箭头是 ES6 的一个特性。它已在 Firefox(Gecko) 中引入,但尚未在其他浏览器中引入(尤其是在 V8 中还没有完全引入,这对于 nodejs/iojs 开发来说很有趣)。这是一个参考文档

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

无论如何,如果您需要范围绑定,那么不要=>使用bind(). 这是一个简单的例子。

而不是这个。

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

用这个。

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

如果您不需要范围绑定,那么只需这样做。

$("#example").on("click", function() {
   console.log("example");
});
于 2015-07-03T05:18:05.450 回答