dragonfly
dragonfly

Reputation: 17773

TypeScript and this context detection

When I add this code inside the constructor (start is the method of the class):

document.getElementById("test").addEventListener, event => {
    this.start();
};

TypeScript is smart enough to know that context of this changes inside the callback:

var _this = this;
document.getElementById("test").addEventListener, function (event) {
    _this.start();
};

However, when I change it to use $("#test").click , this is not held in helper variable anymore, and code will break:

$("#test").on("click", function () {
    this.start();
});

How is it working that in the former example TypeScript does the right thing, but in the latter it does not?

Upvotes: 0

Views: 297

Answers (2)

Ken Smith
Ken Smith

Reputation: 20445

This is as-designed. TypeScript binds the this reference to the containing class in arrow-functions, but uses the JavaScript meaning of this in function(){} functions. See, ad infra, http://piotrwalat.net/arrow-function-expressions-in-typescript/. In other words, the problem isn't with the addEventListener vs the .on('click') syntax, but the fact that in the second, you were using a function(){} instead of an arrow function.

Upvotes: 2

David Sherret
David Sherret

Reputation: 106680

It's because in one it's using an arrow function...

document.getElementById("test").addEventListener(event => {
    this.start();
});

...and the other is using a function expression...

$("#test").on("click", function() {
    this.start();
});

To fix it, change the callback to an arrow function:

$("#test").on("click", () => {
    this.start();
});

Upvotes: 2

Related Questions