Reputation: 63
In second code "Bird.prototype and Dog.prototype is not instance of Animal"
Why is so? No such problem in first code.
//First
function Animal() { }
function Bird() { }
function Dog() { }
Bird.prototype = Object.create(Animal.prototype);
Dog.prototype = Object.create(Animal.prototype);
// Only changes in code below this line
Bird.prototype.constructor=Bird;
Dog.prototype.constructor=Dog;
let duck = new Bird();
let beagle = new Dog();
//Second
function Animal() { }
function Bird() { }
function Dog() { }
Bird.prototype = Object.create(Animal.prototype);
Dog.prototype = Object.create(Animal.prototype);
// Only change code below this line
Bird.prototype={constructor:Bird};
Dog.prototype={constructor:Dog};
let duck = new Bird();
let beagle = new Dog();
Upvotes: -1
Views: 50
Reputation: 943108
In the first example you modify the object assigned to prototype
.
In the second example you replace it.
const thing = { a: "value" };
const a = {};
const b = {};
a.example = Object.create(thing);
b.example = Object.create(thing);
a.example.b = "other";
b.example = { different: "object" };
console.log( { a, b } );
Upvotes: 3