如何使用回调函数在 TypeScript 中保留词法范围

2024-01-01

我有一个 TypeScript 类,其中有一个我打算用作回调的函数:

removeRow(_this:MyClass): void {
    ...
    // 'this' is now the window object
    // I must use '_this' to get the class itself
    ...
}

我将它传递给另一个函数

this.deleteRow(this.removeRow);

它依次调用 jQuery Ajax 方法,如果成功,则调用回调,如下所示:

deleteItem(removeRowCallback: (_this:MyClass) => void ): void {
    $.ajax(action, {
        data: { "id": id },
        type: "POST"
    })
    .done(() => {
        removeRowCallback(this);
    })
    .fail(() => {
        alert("There was an error!");
    });
}

我可以保留对我的类的“this”引用的唯一方法是将其传递给回调,如上面所示。它有效,但它是裤子代码。如果我没有像这样连接“this”(抱歉),那么回调方法中对 this 的任何引用都将恢复为 Window 对象。因为我一直使用箭头函数,所以我期望“this”是类本身,就像它在类中的其他地方一样。

有人知道如何在 TypeScript 中传递回调,保留词法范围吗?


2014年1月28日编辑:

新读者请务必查看下面扎克的回答 https://stackoverflow.com/a/21386201/81723.

他有一个更简洁的解决方案,可以让您使用粗箭头语法在类定义中定义和实例化作用域函数。

我唯一要补充的是,关于option 5在 Zac 的回答中,可以使用以下语法指定方法签名和返回类型,而无需重复:

public myMethod = (prop1: number): string => {
    return 'asdf';
}

2013年5月28日编辑:

定义函数属性类型的语法已更改(自 TypeScript 版本 0.8 起)。

以前您可以定义这样的函数类型:

class Test {
   removeRow: (): void;
}

现在已更改为:

class Test {
   removeRow: () => void;
}

我已在下面更新了我的答案以包含此新更改。

进一步说一句:如果您需要为同一函数名定义多个函数签名(例如运行时函数重载),那么您可以使用对象映射表示法(这在 jQuery 描述符文件中广泛使用):

class Test {
    removeRow: {
        (): void;
        (param: string): string;
    };
}

您需要定义签名removeRow()作为类的属性,但在构造函数中分配实现。

您可以通过几种不同的方法来执行此操作。

Option 1

class Test {

    // Define the method signature here.
    removeRow: () => void;

    constructor (){
        // Implement the method using the fat arrow syntax.
        this.removeRow = () => {
            // Perform your logic to remove the row.
            // Reference `this` as needed.
        }
    }

}

如果你想让你的构造函数保持最小,那么你可以只保留removeRow类定义中的方法,只需在构造函数中分配一个代理函数:

Option 2

class Test {

    // Again, define the method signature here.
    removeRowProxy: () => void;

    constructor (){
        // Assign the method implementation here.
        this.removeRowProxy = () => {
            this.removeRow.apply(this, arguments);
        }
    }

    removeRow(): void {
        // ... removeRow logic here.
    }

}

Option 3

最后,如果您使用像 underscore 或 jQuery 这样的库,那么您可以使用它们的实用方法来创建代理:

class Test {

    // Define the method signature here.
    removeRowProxy: () => void;

    constructor (){
        // Use jQuery to bind removeRow to this instance.
        this.removeRowProxy = $.proxy(this.removeRow, this);
    }

    removeRow(): void {
        // ... removeRow logic here.
    }

}

然后你就可以整理你的deleteItem方法一点:

// Specify `Function` as the callback type.
// NOTE: You can define a specific signature if needed.
deleteItem(removeRowCallback: Function ): void {
    $.ajax(action, {
        data: { "id": id },
        type: "POST"
    })

    // Pass the callback here.
    // 
    // You don't need the fat arrow syntax here
    // because the callback has already been bound
    // to the correct scope.
    .done(removeRowCallback)

    .fail(() => {
        alert("There was an error!");
    });
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用回调函数在 TypeScript 中保留词法范围 的相关文章