2

I have two version code

    let Animal = function()
    {

    }

    Animal.prototype.voice = "Miau"


    let Cat = function()
    {

    }
    Cat.prototype = Object.create(Animal.prototype);

    let flippy = new Cat();

    console.log(flippy.voice)

This version vorked and return "Miau" but second version

let Animal = function()
{
   this.voice = "Miau"
}


let Cat = function()
{

}
Cat.prototype = Object.create(Animal.prototype);

let flippy = new Cat();

console.log(flippy.voice)

Worked but return false Why I cant call flippy.voice? and how call flippy.voice?

1 Answer 1

4

Why I cant call flippy.voice?

Because there is no voice on flippy, because no code has ever been run that would have created it.

When deriving constructors in JavaScript, it's important to call the super's constructor from the sub's constructor:

let Cat = function() {
    Animal.call(this); // <====
};

If you do that, then the code in Animal is run, and the instance will have a voice property.

Note: It's also useful to fix up the constructor property on Cat.prototype:

let Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat; // <===

That said, having Animal set the voice to "Miau" seems...wrong. Perhaps accept it as an argument?

let Animal = function(voice) {
    this.voice = voice;
};

let Cat = function() {
    Animal.call(this, "Miau");
};

let Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;

let flippy = new Cat();
console.log(flippy.voice); // "Miau"

Of course, here in 2017, you can use class syntax (transpiling if necessary for older target environments) to simplify:

class Animal {
    constructor(voice) {
        this.voice = voice;
    }
}

class Cat extends Animal {
    constructor() {
        super("Miau");
    }
}

let flippy = new Cat();
console.log(flippy.voice); // "Miau"
Sign up to request clarification or add additional context in comments.

2 Comments

I think extends with Object.create(function.prototype) the same thing
@MuradSofiyev: The same thing as what? It's not the same thing as calling Animal from Cat, and it doesn't set constructor to the right value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.