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"