javascriptprototyping

JavaScript protyping - differences


Here's my sample code

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype  = {
  constructor: Person,
  printInformation: function() {
    console.log(this.toString());
  },
  toString: function() {
    return "Name: " + this.name + ", Age: " + this.age;
  }
};

var person1 = new Person("Some Name", 15);
person1.printInformation();
console.log(typeof(person1));
console.log(Object.getPrototypeOf(person1) === Object.prototype);

var book = {
  title: "Some book",
  author: "Some author",
  printInformation: function() {
    console.log(this.toString());
  },
  toString: function() {
    return "Book: " + this.title + ", Author(s): " + this.author;
  }
};

book.printInformation();
var bookPrototype = Object.getPrototypeOf(book);
console.log(typeof(book));
console.log(Object.getPrototypeOf(book) === Object.prototype);

Output:

Name: Some Name, Age: 15
object
false
Book: Some book, Author(s): Some author
object
true

Why does Object.getPrototypeOf(person1) === Object.prototype return false while Object.getPrototypeOf(book) === Object.prototype return true?

Both are instances of object, both point to a prototype, I'd hope, both should return true. Kindly enlighten me.


Solution

  • The prototype chain of person1 looks like this:

    person1 ---> Person.prototype ---> Object.prototype ---> null
    

    The prototype chain of book looks like this:

    book ---> Object.prototype ---> null
    

    The Object.getPrototypeOf() method returns the next item in the prototype chain. Therefore, person1 does not return Object.prototype and is therefore false.


    To get the person1 to give true, you'd have to cycle calls until you reached Object.prototype.

    var obj = person1
    
    while (obj) {
        if (obj === Object.prototype) {
            console.log("found it!");
            break;
        }
        obj = Object.getPrototypeOf(obj);
    }
    

    Or if the prototype object is indeed on a function, you could just use instanceof instead.

    person1 instanceof Object; // true
    book instanceof Object; // true
    

    The instanceof searches the prototype chain of the object you provide to see if it has any object that matches the .prototype of the function you provide, which in this case is the Object function.