Calling a method from a class without creating an instance

I'll try to make it clear how I can if you look at frameworks like cocos2d-x for example

cc.Sprite.extend();

      

Sprite a class here how we can call a method without creating it using the new

keyword

I have a class like

var superClass = function(){

    this.init = function(){
        console.log("new class constructed !")
    };

};

      

to call init i have to do this

obj = new superClass();
obj.init();

      

but how can i refer to a class method without instantiating it

+3


source to share


3 answers


Basically, you want to use a static method. There are different ways to achieve this. I think using an object literal would be easier for you.

Litteral object :

var superClass = {
    init: function(){
        console.log("new class constructed !")
    }
};

superClass.init();

      

https://jsfiddle.net/ckgmb9fk/

However, you can still define an object using the constructor of the function 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();

      

Please note that the method init

will not be available on the object instance SuperClass

as it is not on the object's prototype.

https://jsfiddle.net/mLxoh1qj/



Expanding the 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 a function init

from both prototype SuperClass

and object instance.

ES6:

It's much better in ES6

class SuperClass {
   static init() {
     console.log("new class constructed !")
   }
}

SuperClass.init();

      

+7


source


If you assign a method this way, you cannot call it without creating a class, but you can achieve this by extending the prototype:



var superClass = function(){
};

superClass.prototype.init = function(){
    console.log("new class constructed !")
};

var obj = new superClass();
obj.init();
superClass.prototype.init();

      

+1


source


Use superClass

as namespace.

superClass = {
    init: function() { 
    }
}

      

0


source







All Articles