我知道这可能是非常基本的,但我很难理解它。
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
TypeScript 捕获的实现方式是通过箭头函数。引用安德斯的话:
The this
在箭头函数中是词法作用域的
这是我喜欢利用它来发挥我的优势的方式:
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;
}
在 TypeScript Playground 中查看此内容 http://www.typescriptlang.org/Playground/#src=class%20test%7B%0A%09%2F%2F%20Use%20arrow%20functions%0A%09func1%3D(arg%3Astring)%3D%3E%7B%0A%09%09%09return%20arg%2B%22%20yeah%22%20%2B%20this.prop%3B%0A%09%7D%0A%09func2%3D(arg%3Anumber)%3D%3E%7B%0A%09%09%09return%20arg%2B10%20%2B%20this.prop%3B%0A%09%7D%09%09%0A%09%09%0A%09%2F%2F%20some%20property%20on%20this%0A%09prop%20%3D%2010%3B%0A%7D
你可以在生成的 JavaScript 中看到this
被捕获outside函数调用:
var _this = this;
this.prop = 10;
this.func1 = function (arg) {
return arg + " yeah" + _this.prop;
};
so the this
函数调用内的值(可以是window
)不会被使用。
了解更多:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)