skip to Main Content
function Animal() {}

function Rabbit() {}
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;

class Rabbit extends Animal {}

console.log(Object.getPrototypeOf(Rabbit) === Animal);

Why do they say these two ways are the same, but there is this difference

2

Answers


  1. The two approaches you’ve mentioned have some key differences:

    1. Function Constructor Approach:
      function Animal() {}
      
      function Rabbit() {}
      Rabbit.prototype = Object.create(Animal.prototype);
      Rabbit.prototype.constructor = Rabbit;
      

    In this approach, you define the Animal and Rabbit functions using the traditional function constructor pattern. You then manually set the prototype of Rabbit to a new object created from Animal.prototype. This establishes the prototype chain, where Rabbit.prototype delegates to Animal.prototype. Finally, you set the constructor property of Rabbit.prototype to Rabbit to ensure that it points back to the correct constructor.

    1. Class Syntax Approach:
      class Animal {}
      class Rabbit extends Animal {}
      

    In this approach, you use the newer class syntax introduced in ES6 to define the Animal and Rabbit classes. The extends keyword is used to create a subclass Rabbit that inherits from Animal. Under the hood, this achieves the same prototype chain setup as the function constructor approach.

    However, in your code snippet, there’s a mistake: class Rabbit extends Animal {} should not be followed by console.log(Object.getPrototypeOf(Rabbit) === Animal);. Rabbit is a class, not an instance, so Object.getPrototypeOf(Rabbit) returns the class constructor’s prototype, not the prototype of an instance of Rabbit.

    Instead, to check if Rabbit’s prototype is the same as Animal.prototype, you should do:

    console.log(Object.getPrototypeOf(Rabbit.prototype) === Animal.prototype);
    

    This will correctly log true, indicating that Rabbit’s prototype is Animal.prototype.

    Login or Signup to reply.
  2. It’s not the same, ES5 prototype inheritance doesn’t call parent constructors, also there’re additional differences if we dig dipper:

    function Animal() {
      this.type = 'animal';
    }
    
    function Rabbit() {}
    
    Rabbit.prototype = Object.create(Animal.prototype);
    Rabbit.prototype.constructor = Rabbit;
    
    const rabbit = new Rabbit();
    console.log(rabbit.type);
    
    {
      class Animal {
        constructor(){
          this.type = 'animal';
        }
      }
    
      class Rabbit extends Animal{}
    
      const rabbit = new Rabbit();
      console.log(rabbit.type);
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search