7

我的编程经验相当丰富,但对 TypeScript 还是很陌生。

尝试将它与 jQuery 一起使用并立即遇到回调的“this”问题(例如 $(document).ready.

使用 $.proxy() 是一种方法,但使用 TypeScript 的箭头 (lambda) 函数似乎要好得多。但我只看到它们用作表达式——即整个函数是内联定义的。我希望能够设置可以作为我的类的方法调用的箭头函数,例如(在伪代码中):

class Something {
    constructor() {
    $(' nav li').click(this.menuClick);
    }
 private menuClick (and this would be an arrow function to preserve 'this')()=>    
  // it would call this.anotherMethod()
  // plus lots of other things so it won't easily fit inline

 private anotherMethod():void {
        // do something on the menu click, several lines perhaps, 
  }

}

我来自 AS3 的 OOP 背景,这就是我能够做到这一点的方式——“this”很容易访问,或者很清楚如何访问它。我热衷于使用 TypeScript 来克服我在使用纯 Javascript 时遇到的 OOP 障碍——但是(对我而言)必须代理所有 jQuery 调用似乎很麻烦(我知道那里有一些类可以做到这一点)我,但是有没有更简单的方法,带有箭头/lambda函数?)。

如果我不理解显而易见的事情,请耐心等待,但这对我来说并不明显!

4

2 回答 2

11

The reason there isn't a way to do this by default is that it's a tremendous runtime cost in terms of per-instance memory consumption if done automatically. Rather than having one base prototype object with all the functions in it and each class instance pointing to that prototype for its function definitions, you end up having a closure per function for every instance of the class.

There might be better type system support for this in the future, but for now, dealing with this binding issues is just a tax you have to pay when writing JavaScript of any flavor. Hopefully as things like TypeScript gain momentum, library authors will reduce their usage of this-stomping (though the DOM will never have that luxury).

The upside is that in TypeScript, it's not a huge amount more code when you do need to re-re-bind this:

$(' nav li').click(() => this.menuClick());

or

$(' nav li').click(this.menuClick.bind(this));

于 2012-12-13T00:01:07.933 回答
2

简短的回答:

如果你改变:$(' nav li').click(this.menuClick);

进入 :$(' nav li').click(() => this.menuClick());

然后this将是menuClick方法中的类“某事”。

于 2012-12-13T09:32:04.617 回答