-1

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();
1
  • instanceof does not depend on constructor, but rather "prototype chain", which is apparently broken by the second approach. See this post for more details Commented Aug 31, 2020 at 19:58

1 Answer 1

3

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 } );

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

Comments

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.