Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The this keyword in typescript. Is it a bug?

Tags:

typescript

I have a member function render(). This function calls another member of the class add(any). This is the snippet.

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

If I use the keyword "this" in add, the type is 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.

like image 980
4Str4ngeG4me Avatar asked Dec 03 '12 12:12

4Str4ngeG4me


People also ask

What is this keyword in TypeScript?

The "this" keyword always points to the object that is calling a particular method. The type of "this" in an expression depends on the location in which the reference occurs: In a constructor, member function, or member accessor, this is of the class instance type of the containing class.

What does this keyword mean in angular?

this refers to the component itself for which the template was rendered. On the template you can access only members of the component. This means that this is implicitly added to each property which you use in the template.

Which items are not proper TypeScript?

Number , String , Boolean , Symbol and Object ❌ Don't ever use the types Number , String , Boolean , Symbol , or Object These types refer to non-primitive boxed objects that are almost never used appropriately in JavaScript code.

Why this keyword is undefined in JavaScript?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .


2 Answers

As JcFx points out, your this scope is different within the each callback.

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:

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

Compiles to the following 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:

render(){
    collection.each(this.add.bind(this));
}
like image 129
JohnnyHK Avatar answered Sep 20 '22 23:09

JohnnyHK


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

Try this:

render(){
    var that = this;
    collection.each(that.add);
}
like image 28
Jude Fisher Avatar answered Sep 23 '22 23:09

Jude Fisher