My Question, see below, is how to declare STATIC functions and constants of a pre-ES6 class so they can be inherited?
A recap of the present ES6 class and pre-ES6 classes are given prior to the question so we are all using the same conventions.
In post ES6 we can define a static function in a class as follows:
class MyClass {
static someMethod () {
console.log('Doing someMethod');
}
}
In pre ES6 I can create a base class as follows:
var MyClassBase = function(str){
this.m_Data = str; // This acts a bit like a constructor where you can assign data within the class
};
You can create an instance pre-ES6 with
var myclassbase = new MyClassBase("Wibble");
You can creat a pre-ES6 non-static member function of that class:
MyClassBase.prototype.EchoData = function(){
console.log(this.m_Data);
}
You need an instance to call that non-static member function:
var myclassbase = new MyClassBase("Wibble");
myclassbase.EchoData();
To inherit, pre-ES6 I would do something like:
var MyClass = function(str){
MyClassBase.call(this, str);
};
MyClass.prototype = new MyClassBase(); // inherit
[EDIT]: However @adiga has suggested in the comments (see their useful links) that a better way is:
var MyClass = function(str){
MyClassBase.call(this, str);
};
MyClass.prototype = Object.create(MyClassBase.prototype);
MyClass.prototype.constructor = MyClass;
That is all background. Now the questions about Statics.
Question: How do I pre-ES6 create static functions in the base class MyClassBase
which can be called without an instance, eg:
MyClassBase.StaticFunctionInMyClassBase();
MyClass.StaticFunctionInMyClassBase(); // This could be the inherited function from MyClassBase,
// or may be a redefined overridden function in MyClass
Question: How do I assign static constants to MyClass
and MyClassBase
pre-ES6 that can be accessed without an instance? For Example,
var result = MyClassBase.TWO_PLUS_TWO; // Echos 4, a predefined static value in MyClassBase
var result = MyClass.TWO_PLUS_TWO; // Echos 5, if TWO_PLUS_TWO has been redefined in MyClass,
// or 4 if TWO_PLUS_TWO has no been redefined in MyClass
Suggestion By Kai: Statics can be included with the following:
var MyClassBase = function(str){
this.m_Data = str;
};
MyClassBase.STATIC_STRING = "Ooops";
However, when I create my class MyClass
which inherits MyClassBase
, then MyClass.STATIC_STRING
is undefined
. I can only access "Ooops" with MyClassBase.STATIC_STRING
. Is that normal class conventions?