Search code examples
javascriptconstructorprototype

How can we use 'new' on a function if not reassigned constructor


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


Solution

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