2

In this prototypal inheritance example, if we skip to reassign the constructor then how can we use a keyword 'new' on it?

According to tutorial the constructor becomes null if we change the prototype to some other object. then which contructor sets the 'this.name' property ?

let animal = {
  eats: true,
  hyponym: "Animal"
};

function Rabbit(name) {
  this.name = name;
  // by default:
  // Rabbit.prototype = { constructor: Rabbit }
}
console.log(
  "Rabbit.prototype.constructor == Rabbit",
  Rabbit.prototype.constructor == Rabbit
); // true

Rabbit.prototype = animal; // constructor = null
// Rabbit.prototype.constructor = Rabbit; // Reassign constructor 

let rabbit = new Rabbit("White rabbit"); //no error

console.log("rabbit.constructor == Rabbit", rabbit.constructor == Rabbit);
console.log("rabbit.name", rabbit.name);
console.log("rabbit.hyponym", rabbit.hyponym); // Animal
Amit Shah
  • 7,771
  • 5
  • 39
  • 55
  • 1
    As stated in the duplicate link, it is **not** a necissity to set the `constructor` back to the function when you assign to the `prototype`. It is only needed when you are planning on using the `.constructor` value later on. – ibrahim mahrir Apr 22 '18 at 08:48
  • @ibrahimmahrir Thanks understood, but which duplicate link? – Amit Shah Apr 22 '18 at 08:53
  • the one I closed your question to (aka the one whose link is at the top of your question now) (aka [**this one**](https://stackoverflow.com/questions/8453887/why-is-it-necessary-to-set-the-prototype-constructor)). – ibrahim mahrir Apr 22 '18 at 08:55

1 Answers1

1

First you have Rabbit.prototype.constructor == Rabbit which is true.

Then when you change prototype to animal doing

Rabbit.prototype = animal;

then the rabbit.prototype.constructor is set to be equal to animal.constructor which is the native Object therefore you have Rabbit.prototype.constructor === Object not null

You can test it.

let animal = {
  eats: true,
  hyponym: "Animal"
};

function Rabbit(name) {
  this.name = name;
  // by default:
  // Rabbit.prototype = { constructor: Rabbit }
}

Rabbit.prototype = animal; // constructor = null
// Rabbit.prototype.constructor = Rabbit; // Reassign constructor
console.log(Rabbit.prototype.constructor);
Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54