Bronzato Bronzato - 2 months ago 7
TypeScript Question

With TypeScript: unable to refer to 'this' (class) from inside a function

I'm learning

TypeScript
and have the following class:

class DetailDriver {

public get driver() {
return super.getEntity();
}

public activate(): breeze.Promise {
var id = this.driver.id(); // this refers to (class) DetailDriver

return promise
.then(getCertificate)
.fail(somethingWrong);

function getCertificate() {
var id = this.driver.id(); // this refers to any
return ...
}
}
}


As you can see on the above code, the first call to
this
refers to my class
DetailDriver
. That's good. The second call to
this
(inside
getCertificate
) refers to
any
. That's not what I need. I need to refer to my class
DetailDriver
.

How to proceed?

Thanks.

Answer

Well,

According to section 4.9.2 of the TypeScript Language Specification you should use fat arrow syntax to preserve the scoping for this.

return promise
        .then(() => return.this.id;)
        .fail(somethingWrong);

Then the this keyword is properly determined to be a Driver.