TypeScript 类继承:'super'只能在派生类或对象文本表达式的成员中引用



我们正在使用具有继承功能的TypeScript类,并且遇到了明显的范围问题。TypeScript/JavaScript 不允许我们从 promise 结构(甚至从封闭函数(中调用"super"。我们收到此错误:

TypeScript:"super"只能在派生类或对象文字表达式的成员中引用

有没有办法解决这个问题?代码如下:

export class VendorBill extends Transaction {
    constructor() {
        super();
    }
    save() {
        let deferred = $.Deferred();
        $.ajax({
            type: "GET",
            url: '/myrestapi',
            success: function (data) {    
                deferred.resolve();    
            },
            error: function (jqXHR: any, textStatus, errorThrown) {
                deferred.reject()
            }
        })
        $.when(deferred).always(function () {
            super.save();  <----------- THIS IS CAUSING THE ERROR
        })    
    }
}

原因是编译器super.save()转到:

_super.prototype.fn.call(this);

但是this不是正确的,因为您传递的函数未绑定到正确的上下文。

您可以使用箭头函数:

$.when(deferred).always(() => {
    super.save();
}) 

最新更新