简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM