在打字稿中,我可以这样写:
$('#something').fadeOut(400, (): void => {
this.invokeAnotherMethod();
});
Run Code Online (Sandbox Code Playgroud)
编译时,TypeScript会自动确保这指向我的类而不是封闭的函数:
var _this = this;
$('#something').fadeOut(400, function() {
_this.invokeAnotherMethod();
});
Run Code Online (Sandbox Code Playgroud)
但是,当我需要访问真实的而不是外部_this时呢?有语法可以参考吗?例如,我如何编写将编译为以下代码:
var _this = this;
$('#something').fadeOut(400, function() {
$(this).data('specialhide', true);
_this.invokeAnotherMethod();
});
Run Code Online (Sandbox Code Playgroud)
可能吗?
Fen*_*ton 26
您需要避免使用fat-arrow语法来执行此操作,因为您不希望保留词法范围this.
var _me = this;
$('#something').fadeOut(400, function () {
_me.invokeAnotherMethod();
$(this).data('specialhide', true);
});
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我使用_me而不是_this避免与TypeScript生成的变量发生任何冲突.我也避免了self,以避免混淆window.self(感谢RockResolve).
ECMAScript 6规范具有箭头函数定义 - 它是TypeScript语言从中获取此功能的地方.当TypeScript将来面向ECMAScript 6时,它将留在() =>语法中 - 因此它们无法在this不破坏未来兼容性的情况下使用它.
即使你能想象他们如何能更改打字稿编译器,使双方_this和this提供的ECMAScript 3或5,它实际上成为6版中的问题.
| 归档时间: |
|
| 查看次数: |
6529 次 |
| 最近记录: |