簡體   English   中英

如何在靜態方法中調用實例方法?

[英]how to call an instance method inside a static method?

我知道我們通常如何調用類的常規方法或類的靜態方法,但我剛剛意識到我不知道如何在靜態方法中調用類的常規方法:|

像這樣的東西

module.exports = class Notification {
  parsing_html(order) {
   // some parsing
  }


  static async send_notification(_id){
    const order = await Order.findOne({ _id });
    this.parsing_html(order);
  }
};

我想用this與否,仍然無法正常工作。

我在這里缺少什么?

在此先感謝您的任何幫助/建議。

在運行時的 javascript 中,沒有“實例方法”或“靜態方法”之類的東西。 整個類/靜態語法只是一個速記。 Javascript OOP 基於原型和構造函數。

class Abc {
   constructor() { ..constructor code.. }
   test() { ... }
   static staticTest() { ... }
}

只是一個速記/更直觀的語法:

function Abc() { ..constructor code.. }
Abc.prototype.test = function() { ... }
Abc.staticTest = function() { ... }

兩個代碼在運行時完全相同。

因此,您始終可以從代碼中的任何位置調用Notification.prototype.parsing_html 但是有一個問題:關鍵字this將始終引用調用該方法的對象(直接在點之前的對象,另請參見: https : //developer.mozilla.org/en-US/docs/Web/JavaScript /Reference/Operators/this ),箭頭函數除外。 在這種情況下Notification.prototype將是this對函數調用可能導致意外的行為。 您可以設置的是this通過callapplyNotification.prototype.parsing_html.call(yourThisObject, order);

module.exports = class Notification {
  parsing_html(order) {
   // some parsing
  }

  static async send_notification(_id){
    const order = await Order.findOne({ _id });
    Notification.prototype.parsing_html(order); 
  }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM