我可以在TypeScript lambda中访问另一个吗?

我可以在TypeScript lambda中访问另一个吗?,typescript,Typescript,在typescript中,我可以这样写: $('#something').fadeOut(400, (): void => { this.invokeAnotherMethod(); }); 编译时,TypeScript会自动确保它指向我的类,而不是封闭的函数: var _this = this; $('#something').fadeOut(400, function() { _this.invokeAnotherMethod(); }); 但是,当我需要访问真实的

在typescript中,我可以这样写:

$('#something').fadeOut(400, (): void => {
    this.invokeAnotherMethod();
});
编译时,TypeScript会自动确保它指向我的类,而不是封闭的函数:

var _this = this;
$('#something').fadeOut(400, function() {
    _this.invokeAnotherMethod();
});
但是,当我需要访问真实的this而不是外部的this时呢?是否有引用它的语法?例如,我如何编写可编译为以下内容的代码:

var _this = this;
$('#something').fadeOut(400, function() {
    $(this).data('specialhide', true);
    _this.invokeAnotherMethod();
});

有可能吗?

您需要避免使用胖箭头语法来执行此操作,因为您不想保留
的词法范围

var _me = this;
$('#something').fadeOut(400, function () {
    _me.invokeAnotherMethod();
    $(this).data('specialhide', true);
});
在本例中,我使用了
\u me
而不是
\u this
来避免与TypeScript生成的变量发生任何冲突。我还避免了
self
,以避免与
window.self
混淆(感谢RockResolve)

为什么! ECMAScript 6规范的特点是箭头函数定义——TypeScript语言就是从这里获得这一特性的。当TypeScript将来以ECMAScript 6为目标时,它将以
()=>
语法离开,因此它们无法在不破坏未来兼容性的情况下使它在
的两个上下文中都工作


尽管您可以想象他们如何更改TypeScript编译器,使其在ECMAScript 3或5中同时使用
\u this
this
,但在版本6中,这实际上会成为一个问题。

我找到了一个解决方法,如以下我的回答所述:

这是实现史蒂夫·芬顿在回答中所做的终结的更好方式。我更喜欢它,因为方法签名记录了使用情况

基本上,使用如下方法:

fadeOutLambda(outerThis: YourClass): {(d: number, i: number): number}{
    return function(d: number, i: number){
        // Put your "fadeOut" logic here
        // refer to "this" to mean the dynamically scoped "this"
        // refer to "outerThis" to refer to the class instance
        alert(outerThis); // lexically scoped class instance
        alert(this); // dynamically scoped context caller
        return 999;
    }
}

让我提供另一个不使用lambda的解决方案。 可以将主节点作为属性(在本例中称为“我”)附加到此属性


谢谢,这正是我目前正在做的,隐藏
self
,并且在没有箭头功能的情况下使用它。我只是想知道是否还有其他方法。小心使用“自我”这个词。内置的窗口变量“self”可能会引起混淆(调试时它让我感到困惑),最好选择另一个词。您也可以通过简单地获取此变量的局部变量来避免传入“outerThis”,从而简化对fadeOutLambda的调用。e、 fadeOutLambda(){var that=this;return function(){…};}我做了一个“照我说的做,不要照我做的做”,因为Tyson提供的方法就是我对大多数lambda函数所做的方法。使用outerThis作为参数是为了明确提醒调用方不能按原样调用该方法来执行计算,必须调用其结果函数。也就是说,我们称之为这个。IDE会提醒程序员这一点,而如果我们使用“var that=this”作为闭包,则不会有任何提醒。防御性编程,防止使用fadeOutLambda()而不是this.fadeOutLambda(),如果他们想直接调用它。
class MyClass
{
    constructor()
    {
        var button: HTMLElement = document.getElementById("buttonID");
        (button as any).me = this;
        button.onclick = this.buttonClick;
    }

    private buttonClick(e): boolean
    {
        var me: MyClass = (this as any).me;

        // Implementation using this (the button) and me (the class)

        return false;
    }
}