"this" in a method call in TypeScript?

How do I make this work:

class TestClass { doMethod1 (arg1, arg2, cb) { this.doMethod2(arg1, arg2, function (result){cb (result)}); } doMethod2 (arg1, arg2, cb) { this.doMethod3(arg1, arg2, function(result){cb (result)}); } doMethod3 (arg1, arg2, cb) { var result = arg1 + arg2; cb(result); } } 

test = new TestClass;

test.doMethod3 (1,1, cb); test.doMethod2 (1,1, CB);

Both work.

test.doMethod1 (1,1, CB);

EDIT: It actually works.

I circumvented related lexical issues using the bold arrow syntax:

 doMethod1 (arg1, arg2, cb) { this.doMethod2(arg1, arg2, (result) => {cb (result)}); } 

Ensures that "this" in doMethod1 matches the "this" in the anonymous callback function.

+4
source share
1 answer

To preserve the lexical coverage of this in TypeScript, you use arrow function expressions.

They are defined in section 4.9.2 of the TypeScript language specification.

 ArrowFormalParameters => { return AssignmentExpression ; } 

Which code might look like this:

 () => { alert(this.arg1); } 
+9
source

Source: https://habr.com/ru/post/1442223/


All Articles