如何访问jQuery .each" s"这"在TypeScript?

时间:2016-03-27 17:42:56

标签: javascript jquery typescript

给出以下TypeScript代码片段:

export class MyClass {
    myMethod() {
       // ...
       $myQuery.each(function(idx, elm) {
           $(this)... // Original javascript code which obviously not correct in typescript
       }
    }
}

然而在TypeScript中这是一个类方法"这个"总是指类实例。我想访问与纯javascript中相同的对象。

一般情况下:使用TypeScript时在回调中访问原始javascript上下文(this)的方法是什么?

1 个答案:

答案 0 :(得分:2)

这不准确。

在lambda表达式或类方法中使用this时,它引用类本身。例子:

class A{
  public a:number;
  public foo(){
     this.a = 1;//this here is A
     var lambda = () => { this.a = 2; } //this here is A
     var fn = function() { this.a = 3; } // this here is not the A
  }
}

您可以在此处查看已转换的代码:Typescript Playground