Krishnan Sriram
Krishnan Sriram

Reputation: 5489

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.

Upvotes: 2

Views: 53

Answers (2)

Moby
Moby

Reputation: 680

With your Person prototype, you're explicitly defining as a 'Person' type object, where as with your book, it is just a generic object that happens to have a variable name of book.

Object.getPrototypeOf(book)

Console outputs Object {}

Object.getPrototypeOf(person1)

Console outputs Person {}

Person is not the same as Object and thus the check for equality returns false.

Upvotes: 0

user1106925
user1106925

Reputation:

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.

Upvotes: 3

Related Questions