Muthu Ganapathy Nathan
Muthu Ganapathy Nathan

Reputation: 3307

Achieving prototype inheritance with private variable in parent object

I tried to achieve the prototypical inheritance, in when there is private variables in parent object.

Consider a code like,

function Piece(isLiveArg) { 
    var isLive = isLiveArg; // I dont wish to make this field as public. I want it to be private.
    this.isLive = function(){ return isLive;}
}    

Piece.prototype.isLive = function () { return this.isLive(); }       

function Pawn(isLiveArg) { 
    // Overriding takes place by below assignment, and getPoints got vanished after this assignment.
    Pawn.prototype = new Piece(isLiveArg);           
}

Pawn.prototype.getPoints = function(){
    return 1;
}

var p = new Pawn(true);

console.log("Pawn live status : " + p.isLive());

But, no private variable isLive exists on parent object, and only public variables exists, then inheritance can able to achieve this very easily., Like in this link., http://jsfiddle.net/tCTGD/3/.

So, How would I achieve the same prototypical inheritance, in when there is private variables in parent object.

Upvotes: 0

Views: 684

Answers (1)

Felix Kling
Felix Kling

Reputation: 816334

The way you are setting up inheritance is wrong. The assignment to Func.prototype should be outside the constructor. Then, if you apply the parent constructor function to the new "child" object, it will assign the closure to it as well.

Example:

function Piece(isLiveArg) { 
    var isLive = isLiveArg;
    this.isLive = function(){ return isLive;}
}

function Pawn(isLiveArg) { 
     // apply parent constructor
     Piece.call(this, isLiveArg);   
}

// set up inheritance
Pawn.prototype = Object.create(Piece.prototype);
Pawn.prototype.constructor = Pawn;

Pawn.prototype.getPoints = function(){
    return 1;
}

Have a look at Benefits of using `Object.create` for inheritance to get an idea why Object.create is better to set up inheritance.

There is no sense in trying to create prototype functions that access "private properties". Only closures defined in the constructor can access those variables.

Upvotes: 5

Related Questions