This is a keyword in typescript. This is mistake?

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

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

If I use the keyword "this" in add, the type is the window. I expect this to be an instance of a member class.

In the constructor, member function, or member access member, this refers to the instance type of the class class.

+7
source share
2 answers

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

However, if you use the anonymous bold arrow function, which will use the lexical rules for this to get what you are looking for:

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

Compiles 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 for the desired this :

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

I do not think this is a mistake.

You are no longer in the scope of the render() function, but instead in the scope of each() .

Try the following:

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

All Articles