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!");
});
}