How do I want to 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: Actually, it does work.
I got around related lexical scoping issues by using the "fat arrow" syntax:
doMethod1 (arg1, arg2, cb)
{
this.doMethod2(arg1, arg2, (result) => {cb (result)});
}
Ensures that the "this" in doMethod1 is the same as the "this" in the anonymous callback function.
The "this" keyword always points to the object that is calling a particular method. The type of "this" in an expression depends on the location in which the reference occurs: In a constructor, member function, or member accessor, this is of the class instance type of the containing class.
According to the TypeScript docs: void represents the return value of functions which don't return a value. Whenever you see a function returning void , you are explicitly told there is no return value. All functions with no return value have an inferred return type of void .
In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object. Alone, this refers to the global object.
A Function is a block of code that you can use multiple times in an application. It can require one or more parameters. A list of parameters in parentheses, and a block of code in braces. To call a function, you code the function name followed by the function's parameters or arguments in parentheses.
To preserve the lexical scoping 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 in code can look like:
() => { alert(this.arg1); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With