如何在JavaScript中从基类继承静态方法? [英] How to inherit static methods from base class in JavaScript?
本文介绍了如何在JavaScript中从基类继承静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用原型继承方式在JavaScript中实现一些基本的OOP。但是,我发现无法从基类继承静态成员(方法)。
I'm trying to achieve some basic OOP in JavaScript with the prototype way of inheritance. However, I find no way to inherit static members (methods) from the base class.
我们可以使用原型模拟基本类模型:
We can simulate the basic class model by using prototype:
SomeClass = function(){
var private_members;
this.public_method = function(){
//some instance stuff..
};
};
Class.static_method = function(){
//some static stuff;
};
//Inheritance
SubClass = function(){ //sub-class definition };
SubClass.prototype = new Class();
但是, SubClass
不会继承 static_method
来自 Class
。
推荐答案
试试这个:
class BaseClass {
static baseMethod () {
console.log("Hello from baseMethod");
}
}
class MyClass extends BaseClass {
constructor(props) {
super(props);
}
}
Object.assign(MyClass, BaseClass);
他们的关键是 Object.assign
哪个应该是成为每个人最好的朋友。您现在可以使用 MyClass
从 BaseClass
调用任何基本方法,如下所示:
They key is Object.assign
which should be everyone's new best friend. You can now call any base method from BaseClass
using MyClass
as follows:
MyClass.baseMethod();
你可以在这支笔。
享受!
这篇关于如何在JavaScript中从基类继承静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文