我知道这可能是痛苦的基本,但我有一个艰难的时间包围我的头。
- class Main
- {
- constructor()
- {
- requestAnimationFrame(this.update); //fine
- }
- update(): void
- {
- requestAnimationFrame(this.update); //error,because this is window
- }
- }
看起来是这样的情况,我需要一个代理,所以让我们说使用Jquery
- class Main
- {
- constructor()
- {
- this.updateProxy = $.proxy(this.update,this);
- requestAnimationFrame(this.updateProxy); //fine
- }
- updateProxy: () => void
- update(): void
- {
- requestAnimationFrame(this.updateProxy); //fine
- }
- }
但是从Actionscript 3背景来看,我不太确定这里发生了什么。对不起,我不知道JavaScript开始和TypeScript结束。
- updateProxy: () => void
而且,我不相信我是这样做的。最后我想要的是我的类有一个a()函数,需要使用aProxy()访问,因为我觉得我写同样的事情两次?是正常吗?
解决方法
如果你想要“this”捕获的打字的方式,这样做是通过箭头功能。引用安德斯
The this in arrow functions is lexically scoped
我喜欢使用这个我的优势的方式是:
- class test{
- // Use arrow functions
- func1=(arg:string)=>{
- return arg+" yeah" + this.prop;
- }
- func2=(arg:number)=>{
- return arg+10 + this.prop;
- }
- // some property on this
- prop = 10;
- }
你可以看到在生成的javascript“this”被捕获之外的函数调用:
- var _this = this;
- this.prop = 10;
- this.func1 = function (arg) {
- return arg + " yeah" + _this.prop;
- };