[英]Why doesn't a method reference keep track of this?
I am using Babel to transpile an ES2015 class: 我正在使用Babel转换ES2015类:
class Foo {
constructor(foo) {
this.foo = foo;
}
sayFoo() {
console.log(this.foo);
}
}
This class works exactly as I expect if I say something like fooVar.sayFoo()
. 如果我说fooVar.sayFoo()
类的东西,这个类就像我期望的那样fooVar.sayFoo()
。 However, if I try to treat the method like a typical JavaScript function and pass it as a parameter ( element.click(fooVar.sayFoo)
), when the method actually runs its lexical this
is the event object, not the instance of Foo
, so the this.foo
is undefined. 但是,如果我尝试将方法视为典型的JavaScript函数并将其作为参数传递( element.click(fooVar.sayFoo)
),当该方法实际运行其词法时, this
是事件对象,而不是Foo
的实例,所以this.foo
是未定义的。
Instead, since I specified an instance of Foo
, I expected fooVar.sayFoo
to be bound to the value of fooVar
. 相反,由于我指定了一个Foo
实例,我希望fooVar.sayFoo
绑定到fooVar
的值。 I have to write an extra wrapper function for this to work as I expect. 我必须编写一个额外的包装函数,以便按照我的预期工作。
I tried to look through the ES6 spec but couldn't figure out the scoping rules. 我试图查看ES6规范,但无法弄清楚范围规则。 Is this strange scoping behavior correct according to spec, or is it a bug somewhere (eg, in Babel)? 根据规范,这种奇怪的范围行为是否正确,或者它是某个地方的错误(例如,在巴别塔中)?
Is this the correct behavior, even though it seems weird? 这是正确的行为,即使它看起来很奇怪吗?
Yes. 是。 Methods are more or less syntactic sugar for functions assigned to prototype
properties. 对于分配给prototype
属性的函数,方法或多或少具有语法糖。
Only arrow functions treat this
differently. 只有箭头功能对待this
不同。
Instead of writing a wrapper function, however, you can explicitly bind the instance to the method: 但是,您可以显式地将实例绑定到方法,而不是编写包装函数:
element.click(fooVar.sayFoo.bind(fooVar));
See also How to access the correct `this` / context inside a callback? 另请参阅如何在回调中访问正确的`this` / context?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.