Reputation: 8625
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?
Upvotes: 6
Views: 2007
Reputation: 664599
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;
};
Upvotes: 3
Reputation: 71918
When you call getA
from any instance, the value of this
inside it will point to the instance itself. You can achieve what you're looking for if your change the setter code to this:
ParentClass.prototype.setA = function(inp){
ParentClass.prototype.a = inp;
}
Note that calling getA
from an instance of ParentClass will return null
, and the constructor defines an own property a
that will shadow the one from the prototype.
Upvotes: 1