Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript singleton inheritance

I would like to keep a single parent class. all clild classes that inherit the parent class will be able to share the same parent class object. How that can be achieved?

var ParentClass = function(){
    this.a = null;
}

ParentClass.prototype.setA = function(inp){
    this.a = inp;
}

ParentClass.prototype.getA = function(){
    console.log("get a "+this.a);
}

// Clild Class

var ClassB = function(){}

ClassB.prototype = Object.create(ParentClass.prototype);

var b = new ClassB();
b.setA(10);
b.getA(); //it will return 10


//Another clild Class
var ClassC = function(){}

ClassC.prototype = Object.create(ParentClass.prototype);
var c = new ClassC();
c.getA(); //I want 10 here.

I understand, as for the second clild class the parent class is instantiating again that is why I can't access the old object. How I can achieve this singleton inheritance in Javascript? Any idea?

like image 635
Hasanavi Avatar asked Oct 02 '22 23:10

Hasanavi


1 Answers

Put such static values somewhere else. this is the current instance, and that's not where you want to create a new property. Choices are:

  • ParentClass.prototype (as demonstrated by @bfavaretto), which will lead to all instances inheriting and being able to overwrite it
  • a scoped variable (implementing the revealing module pattern basically):

    (function() {
        var a;
        ParentClass.prototype.setA = function(inp){
            a = inp;
        };
        ParentClass.prototype.getA = function(){
            console.log("get a "+a);
            return a;
        };
    }());
    
  • the ParentClass function object itself:

    ParentClass.prototype.setA = function(inp){
        ParentClass.a = inp;
    };
    ParentClass.prototype.getA = function(){
        console.log("get a "+ParentClass.a);
        return ParentClass.a;
    };
    
like image 97
Bergi Avatar answered Oct 07 '22 19:10

Bergi