简体   繁体   English

打字稿中的this关键字。 是虫子吗?

[英]The this keyword in typescript. Is it a bug?

I have a member function render(). 我有一个成员函数render()。 This function calls another member of the class add(any). 该函数调用类add(any)的另一个成员。 This is the snippet. 这是代码段。

render(){
    collection.each(this.add);
}

If I use the keyword "this" in add, the type is window. 如果我在添加中使用关键字“ this”,则类型为window。 I would expect it to be the instance of the member class. 我希望它是成员类的实例。

In a constructor, member function, or member accessor, this is of the class instance type of the containing class. 在构造函数,成员函数或成员访问器中,这是包含类的类实例类型。

As JcFx points out, your this scope is different within the each callback. 作为JcFx指出,你的this范围内的不同each回调。

However, if you use a 'fat arrow' anonymous function, that will use lexical scoping rules for this so that you get what you're looking for: 但是,如果您使用“胖箭头”匿名函数,则它将this使用词法作用域规则,以便获得所需的内容:

render(){
    collection.each((x) => this.add(x));
}

Compiles to the following JavaScript: 编译为以下JavaScript:

X.prototype.render = function () {
    var _this = this;
    collection.each(function (x) {
        return _this.add(x);
    });
}

Another option is to explicitly bind the add call to the desired this : 另一个选择是bind add调用显式bind到所需的this

render(){
    collection.each(this.add.bind(this));
}

I don't think it's a bug. 我不认为这是一个错误。

You are no longer in the scope of the render() function, but instead in the scope of each() . 您不再在render()函数的范围内,而是在each()的范围内。

Try this: 尝试这个:

render(){
    var that = this;
    collection.each(that.add);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM