I’ve got some TypeScript code that (effectively) looks like this:
class User {
name: string = "Bob";
sayHello(): void {
console.log("Hello, " + this.name);
}
}
class RegisteredUser extends User {
name: string = "Frank";
sayHello(): void {
var s = super;
setTimeout(() => s.sayHello(), 1000);
}
}
var registeredUser = new RegisteredUser();
registeredUser.sayHello();
The problem is that TypeScript (inexplicably, IMO) follows the weird JavaScript rules about “this” instead of doing it how every other programming language in the world does it. And so when User.sayHello() is called from the override in RegisteredUser.sayHello(), the this points to the User class rather than to the instantiated RegisteredUser object, so that what is actually logged is:
Hello, undefined
Beyond the fact that this doesn’t make any sense to me to do it this way (see https://typescript.codeplex.com/workitem/477), what’s the best way to work around this, so that this in User.sayHello() is pointing to the right object when called from a callback?
This also works and gets rid of the need for the
svar: