打字稿"this"在类方法中 [英] Typescript "this" inside a class method
问题描述
我知道这可能是非常痛苦的基本工作,但是我很难缠着它.
I know this is probably painfully basic, but i am having a tough time wrapping my head around it.
class Main
{
constructor()
{
requestAnimationFrame(this.update); //fine
}
update(): void
{
requestAnimationFrame(this.update); //error, because this is window
}
}
似乎是需要代理的情况,所以可以说使用Jquery
It appears to be the case that I need a proxy, so lets say using 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的结尾.
But coming from an Actionscript 3 background, I am not really sure what is happening here. Sorry I am not sure where Javascript begins and TypeScript ends.
updateProxy: () => void
而且,我不确信自己在做这项权利.我想要的最后一件事是我的大多数班级都有一个a()函数,需要用aProxy()
访问,因为我感觉自己在写两次相同的东西?正常吗?
And also, I am not convinced I am doing this right. The last thing I want is most of my class having a a() function which needs to be accessed with aProxy()
as I feel I am writing the same thing twice? Is it normal?
推荐答案
如果要this
捕获TypeScript的实现方法,则通过箭头功能.引用安德斯的话:
If you want this
captured the TypeScript way of doing this is via arrow functions. To quote Anders:
箭头功能中的
this
在词法范围内
这是我喜欢利用此优势的方式:
Here is the way I like to use this to my advantage:
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
中捕获了外部函数调用:
You can see that in the generated JavaScript this
is captured outside the function call:
var _this = this;
this.prop = 10;
this.func1 = function (arg) {
return arg + " yeah" + _this.prop;
};
,因此不会使用函数调用内的this
值(可能为window
).
so the this
value inside the function call (which could be window
) would not be used.
要了解更多信息:在TypeScript中理解this
"(4:05 )– YouTube
To learn more: "Understanding this
in TypeScript" (4:05) – YouTube
这篇关于打字稿"this"在类方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!