【问题标题】:How to access jQuery .each's "this" in TypeScript?如何在 TypeScript 中访问 jQuery .each 的“this”?
【发布时间】:2016-07-15 00:20:39
【问题描述】:

给定以下 TypeScript 代码 sn-p:

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

然而,在 TypeScript 中,类方法中的 this 总是指类实例。我想访问与纯 JavaScript 相同的对象。

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

【问题讨论】:

  • 如果我明白了,你想用榆树代替这个吗?
  • “但是在 TypeScript 中,类方法中的 this 总是指类实例。” 你确定吗?这似乎与 JavaScript 有很大的不同。 OTOH,我不知道打字稿。
  • @FelixKling 是的,我确定。积极的。
  • @JonathanLonowski:非常感谢。我的错,我在使用 lambdas “()=> {}” 而不是 “function () {}” 时混合了 TypeScrip 的行为 最好的方法是删除这个愚蠢的问题,但不幸的是我不能,因为它有答案.因此,您发布此评论作为答案的最佳选择。
  • @FelixKling:你是对的。我的坏

标签: javascript jquery typescript


【解决方案1】:

不准确。

在 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

【讨论】:

    猜你喜欢
    • 2015-12-18
    • 2017-03-14
    • 2016-05-17
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 2013-02-23
    相关资源
    最近更新 更多