Search code examples
javascriptinheritanceprototypal-inheritance

Fix for constructor property in protypical inheritence


The book "JavaScript for Ninja" suggested the following fix for constructor property while establishing prototypical chain between objects:

enter image description here

If I create a Person object as follow:

var person = new Person();
alert(person.constructor == Ninja); // Display true

Even though its fix the problem that ninja.constructor will refer to the Ninja function, But it creates the another problem that now person.constructor will also refer to the Ninja function instead of Person.

Reproducible Example:

function Person() {

}
var person = new Person();
Person.prototype.dance = function() {};

function Ninja() {

}
Ninja.prototype = person;
Object.defineProperty(Ninja.prototype, "constructor", {
  enumerable: false,
  value: Ninja,
  writable: true
})
var ninja = new Ninja();

alert(person.constructor == Ninja); // Display true

I am unable to understand why this fix was suggested by the author.


Solution

  • You're only modifying the constructor property of that one person instance, not the whole Person class. If you do

    person2 = new Person();
    console.log(person2.constructor == Ninja);
    

    it will print false.

    Notice that in the book you quoted, it didn't even assign the new Person() object to a variable, it just created an anonymous object for use in creating the prototype chain.

    In general, the object used in the prototype chain will not usually be used as an actual object in the application, it just serves the purpose of linking the related classes.

    function Person() {
    }
    var person = new Person();
    Person.prototype.dance = function() {};
    
    function Ninja() {
    }
    Ninja.prototype = person;
    Object.defineProperty(Ninja.prototype, "constructor", {
      enumerable: false,
      value: Ninja,
      writable: true
    })
    var ninja = new Ninja();
    
    var person2 = new Person();
    console.log(person.constructor == Ninja);
    console.log(person2.constructor == Ninja);