ES6 and newer:
Use the static
keyword. It's supported by most modern browsers.
class SuperClass {
static init() {
console.log("new class constructed !")
}
}
SuperClass.init();
Older browsers:
There are different ways to achieve that. One option is to use an object literal.
Object literal:
var superClass = {
init: function(){
console.log("new class constructed !")
}
};
superClass.init();
https://jsfiddle.net/ckgmb9fk/
However, you can still define an object using a function constructor and then add a static method to the "class". For example, you can do this:
var SuperClass = function(){};
SuperClass.prototype.methodA = function() {
console.log("methodA");
};
SuperClass.init = function() {
console.log("Init function");
}
SuperClass.init();
var sc = new SuperClass();
sc.methodA();
Note that the method init
won't be available in the SuperClass
instance object because it is not in the object prototype.
https://jsfiddle.net/mLxoh1qj/
Extending prototype:
var SuperClass = function(){};
SuperClass.prototype.init = function() {
console.log("Init");
};
SuperClass.prototype.init();
var sc = new SuperClass();
sc.init();
https://jsfiddle.net/0ayct1ry/
This solution is useful if you want to access the function init
both from the SuperClass
prototype and from an object instance.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…