Jos*_*ulf 6 closures typescript
我该如何做这项工作:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
test = new TestClass;
test.doMethod3(1,1,cb); test.doMethod2(1,1,CB);
两者都有效.
test.doMethod1(1,1,CB);
编辑:实际上,它确实有效.
我使用"胖箭头"语法解决了相关的词法范围问题:
doMethod1 (arg1, arg2, cb)
{
this.doMethod2(arg1, arg2, (result) => {cb (result)});
}
Run Code Online (Sandbox Code Playgroud)
确保doMethod1中的"this"与匿名回调函数中的"this"相同.
Fen*_*ton 11
要保留thisTypeScript中的词法作用域,请使用箭头函数表达式.
它们在TypeScript语言规范的4.9.2节中定义.
ArrowFormalParameters => { return AssignmentExpression ; }
Run Code Online (Sandbox Code Playgroud)
在代码中看起来像:
() => { alert(this.arg1); }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3195 次 |
| 最近记录: |