为什么方法参考没有跟踪? [英] Why doesn't a method reference keep track of this?

查看:169
本文介绍了为什么方法参考没有跟踪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Foo {
constructor(foo){
this.foo = foo;
}

sayFoo(){
console.log(this.foo);
}
}

这个类的工作原理与我预期的一样,如果我说的话像 fooVar.sayFoo()。但是,如果我尝试像典型的JavaScript函数一样对待方法,并将其作为参数( element.click(fooVar.sayFoo))传递,那么当该方法实际运行时词汇这个是事件对象,而不是 Foo 的实例,所以 this.foo 未定义。



相反,由于我指定了一个 Foo 的实例,我预计 fooVar.sayFoo 被绑定到 fooVar 的值。我必须编写一个额外的包装函数,这样才能正常工作。



我试图查看ES6规范,但无法弄清楚范围规则。这个奇怪的范围行为是否符合规范,还是在某个地方出现错误?(例如,在巴别尔)?

解决方案


这是正确的行为,即使看起来很奇怪吗?


是的。方法对于分配给原型属性的函数来说,或多或少是语法糖。



只有箭头函数处理这个不同。



但是,您可以将实例显式绑定到方法,而不是编写包装器函数:

  element.click(fooVar.sayFoo.bind(fooVar)); 

另请参见如何在回调中访问正确的this/ context?


I am using Babel to transpile an ES2015 class:

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(). 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.

Instead, since I specified an instance of Foo, I expected fooVar.sayFoo to be bound to the value of 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. Is this strange scoping behavior correct according to spec, or is it a bug somewhere (e.g., 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.

Only arrow functions treat this differently.

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?

这篇关于为什么方法参考没有跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆