Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  160] [ 4]  / answers: 1 / hits: 24233  / 13 Years ago, sat, march 26, 2011, 12:00:00

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


However, SubClass doesn't inherit static_method from Class.


More From » oop

 Answers
20

Try this:



class BaseClass {
static baseMethod () {
console.log(Hello from baseMethod);
}
}

class MyClass extends BaseClass {
constructor(props) {
super(props);
}
}

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


You can see this live and in action on this pen.



Enjoy!


[#93066] Thursday, March 24, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
parker

Total Points: 259
Total Questions: 109
Total Answers: 97

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;