1

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Hi -- great answer, thanks! Is there a better way to encapsulate prototypal classes? I don't like how the constructor method and then the prototype code are all separated out.
@Prefix Well, that is actually the best way. Because, whatever is in the constructor will be created everytime you create an object. So, it is better to put the functions in the prototype and all the instance specific data in the constructor.
@Prefix You might also want to read this
what is the advantage of Cylon.call(this,model); over this.__proto__= new Cylon(model);?
@Prefix Two things. 1) __proto__ is deprecated, 2) You are creating a new object and sticking that as the prototype. You are mixing instance and the prototypes.
|

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.