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?
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 ita 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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With