tdc
tdc

Reputation: 5464

basic / efficient Prototypical inheritance in JavaScript?

So I currently have the following code snippet. I am trying to create a Cylon class, which contains a model property and a prototype attack() method. I am creating a HumanSkin class, which inherits from the Cylon, and also adds its own prototype infiltrate() method.

function Cylon(model){
  this.model = model;
}

Cylon.prototype.attack = function(){
    return("Destroy all humans!");
}

function HumanSkin(){}
HumanSkin.prototype = new Cylon();
HumanSkin.prototype.infiltrate = function(){
  return("Infiltrate the colonies");
}

cylon = new Cylon("raider");
caprica = new HumanSkin(6);

My issue is this -- why is console.log(caprica.model); returning Undefined? How can I easily get full inheritance (preferably with encapsulation) in JS?

Upvotes: 1

Views: 65

Answers (1)

thefourtheye
thefourtheye

Reputation: 239473

When you say,

HumanSkin.prototype = new Cylon();

you are creating a new object of Cylon, with an empty model (undefined). So, inheriting from Cylon, could be improved like this

HumanSkin.prototype = Object.create(Cylon.prototype);

Note that, When you inherit with prototypal inheritance, whatever is in the prototype of the parent will be available to the child. But model is in the Cylon's constructor. Normally, this can be solved like this

function HumanSkin(model) {
    Cylon.call(this, model);
}

Now, whenever you construct a new HumanSkin object, internally Cylon function will be invoked with the current object (this) and the model will be passed as an argument to that. So, Cylon will be initializing the model in the current object.

Upvotes: 5

Related Questions