1

在原型扩展中使用箭头函数时,我得到了我认为的意外行为。

function ES6Example(){}
ES6Example.prototype.foo = function(bar){
  return ((baz) => {
    console.log(this)
    this.bar = baz
  })(bar)
}

var es6Example = new ES6Example
es6Example.foo('qux')

console.info(es6Example.bar)

上面的代码导致全局上下文被打印出来,以及es6Example.bar未定义。这是旧的行为。根据我在 MDN 中看到的文档,我希望这将绑定到实例。我使用 Harmony 标志使用 Node v0.11.15 运行上述代码。请注意,以下操作确实有效:

function ES6Example(){
    this.foo = baz => {
      this.bar = baz
    }
}
4

1 回答 1

2

V8 实现仍然不完整,仍然没有 lexical this

这就是为什么在 Chrome node.js 和 io.js 中,您必须设置一个特殊的“和谐”参数才能使用它:它还没有准备好用于一般消费。

于 2015-01-25T18:22:57.937 回答