我如何使这项工作:
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.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)});
}
确保 doMethod1 中的“this”与匿名回调函数中的“this”相同。