2017-02-10 652 views
0

我們正在使用具有繼承功能的TypeScript類,並且已經遇到明顯的範圍界定問題。 TypeScript/JavaScript不允許我們從承諾結構(甚至是封閉函數)中調用'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 
     })  
    } 
} 
+0

另外值得指出的是您在使用使用額外的延遲對象的承諾,反模式,當你不需要一個。你可以做'$ .ajax({...})。always(()=> {super.save();});' – Adam

回答

3

的原因是,編譯器開啓super.save()到:

_super.prototype.fn.call(this); 

this是不正確的,因爲一個要傳遞未綁定到一個函數正確的背景。

您可以使用arrow function

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

工作正常!謝謝 – ASA2

相關問題