如何在静态方法中调用实例方法



我知道我们通常如何调用类的正则方法或类的静态方法,但我刚刚意识到我不知道如何在静态方法中调用类的常规方法:|

像这个

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。您可以使用callapply:Notification.prototype.parsing_html.call(yourThisObject, order);设置什么是this

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

最新更新