6

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?

1
  • I think you can leave away all the inheritance from your question. The singleton pattern doesn't even work currently if b and c were instances of ParentClass. Commented Sep 11, 2013 at 22:58

2 Answers 2

3

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;
    };
    
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.