1
//I have this base Rectangle constructor function
function Rectangle (length, width){
    this.length = length;
    this.width = width;
}

Rectangle.prototype.getArea = function (){
    return this.length * this.width;
};

//Creating Square constructor function that will inherit from Rectangle...

function Square(size){
    this.length = size;
    this.width  = size;
}

Square.prototype = new Rectangle(); 
Square.prototype.constructor = Square;

//creating rectangle and square instances
var rect = new Rectangle(5, 10);
var square = new Square(6);

console.log(rect.getArea());  //50
console.log(square.getArea());  //36 

console.log(Rectangle.prototype.isPrototypeOf(Square.prototype)); //true

console.log(Rectangle.prototype.isPrototypeOf(rect)); //true

console.log(Square.prototype.isPrototypeOf(square));  //true

my question is when i do the below console.log(), I expected it to print false. However, I got true.

console.log(Rectangle.prototype.isPrototypeOf(square));  //true

1) Does this mean isPrototypeOf goes to multiple levels?

2) if isPrototypeOf goes multiple levels, what is the point of using isPrototypeOf instead of using instanceof?

I've read this Why do we need the isPrototypeOf at all? but didn't understand how it applies in my use-case.

Community
  • 1
  • 1
Wild Widow
  • 2,359
  • 3
  • 22
  • 34

2 Answers2

2
  1. isPrototypeOf checks if an object is within another object's prototype chain so yes it does go multiple levels

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf

  1. They can be used for the same purpose. You can do square instanceof Square or Square.prototype.isPrototypeOf(square) but as you can see, instanceof has a specific purpose to match objects with their constructors where as isPrototypeOf can be used more broadly to check if any object is within the prototype chain of another.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

Ruben Funai
  • 629
  • 5
  • 5
1

The isPrototypeOf() method tests for an object in another object's prototype chain

Here in Your Code

console.log(Rectangle.prototype.isPrototypeOf(square)); // true

It prints true because Square Method is in the the chain of getArea Method and the getArea is the prototype method of Rectangle

Rectangle.prototype.getArea = function (){
    return this.length * this.width;
};

For Example According to Mozilla Docs

 function Fee() {
  // ...
}

function Fi() {
  // ...
}
Fi.prototype = new Fee();

function Fo() {
  // ...
}
Fo.prototype = new Fi();

function Fum() {
  // ...
}
Fum.prototype = new Fo()

Later on down the road, if you instantiate Fum and need to check if Fi's prototype exists within the Fum prototype chain, you could do this:

var fum = new Fum();
// ...

if (Fi.prototype.isPrototypeOf(fum)) {
  // do something safe
}
Akhilesh Singh
  • 1,724
  • 2
  • 19
  • 35