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
The two approaches you’ve mentioned have some key differences:
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.
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:
This will correctly log true, indicating that Rabbit’s prototype is Animal.prototype.
It’s not the same, ES5 prototype inheritance doesn’t call parent constructors, also there’re additional differences if we dig dipper: