Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inherit static methods from base class in JavaScript?

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.

like image 646
William X Avatar asked Mar 26 '11 09:03

William X


People also ask

Can static method be inherited in JavaScript?

In the classical (OO) inheritance pattern, the static methods do not actually get inherited down. Therefore if you have a static method, why not just call: SuperClass. static_method() whenever you need it, no need for JavaScript to keep extra references or copies of the same method.

Can static functions be inherited from base class?

static member functions act the same as non-static member functions: They inherit into the derived class. If you redefine a static member, all the other overloaded functions in the base class are hidden.

How do you call a static method in inherited class?

A static method is the one which you can call without instantiating the class. If you want to call a static method of the superclass, you can call it directly using the class name.

Can we inherited static method?

Static methods take all the data from parameters and compute something from those parameters, with no reference to variables. We can inherit static methods in Java.


1 Answers

In the classical (OO) inheritance pattern, the static methods do not actually get inherited down. Therefore if you have a static method, why not just call: SuperClass.static_method() whenever you need it, no need for JavaScript to keep extra references or copies of the same method.

You can also read this JavaScript Override Patterns to get a better understanding of how to implement inheritance in JavaScript.

like image 190
DragonDTG Avatar answered Sep 20 '22 15:09

DragonDTG