6

我如何使这项工作:

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”相同。

4

1 回答 1

11

要在 TypeScript 中保留 的词法范围this,您可以使用箭头函数表达式。

它们在 TypeScript 语言规范的第 4.9.2 节中定义。

ArrowFormalParameters => { return AssignmentExpression ; }

代码中的哪个看起来像:

() => { alert(this.arg1); }
于 2012-10-26T08:28:20.390 回答