在原型扩展中使用箭头函数时,我得到了我认为的意外行为。
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
}
}