my question is: why there is difference between all 3 ways of defining inheritance ? and if the first snippet is the most correct one how people before 2015 dealt with new keyword ?
- The first snippet the object y is instance of gorilla and it has the prototype and methods of animal, and animal inherits from object prototype
NOTE:that name, age are defined on the object itself - The second snippet is the same as first snippet but the difference is it has additional properties on the Animal prototype name,age and they both have undefined value duo to new call.
- The third snippet is whole different it has the prototype of Object and it is like it moved every method from the animal prototype to itself.
Consider Looking at these snippets
function Animal(name, age) {
this.name = name;
this.age = age;
}
Animal.prototype.eat = function () {
console.log(`${this.name} is eating!`);
};
function Gorilla(name, age, action) {
Animal.call(this, name, age);
}
Gorilla.prototype = Object.create(Animal.prototype);
Gorilla.prototype.constructor = Gorilla;
var y = new Gorilla("morphy", 50);
console.log(y);
function Animal(name, age) {
this.name = name;
this.age = age;
}
Animal.prototype.eat = function () {
console.log(`${this.name} is eating!`);
};
function Gorilla(name, age, action) {
Animal.call(this, name, age);
}
Gorilla.prototype = new Animal();
Gorilla.prototype.constructor = Gorilla;
var y = new Gorilla("morphy", 50);
console.log(y);
function Animal(name, age) {
this.name = name;
this.age = age;
}
Animal.prototype.eat = function () {
console.log(`${this.name} is eating!`);
};
function Gorilla(name, age, action) {
Animal.call(this, name, age);
}
Gorilla.prototype = Animal.prototype;
Gorilla.prototype.constructor = Gorilla;
var y = new Gorilla("morphy", 50);
console.log(y);