Difference among instaceof,constructor property,isPrototypeOf

function Person(name){
    this.name=name;
}
Person.ptototype={
   constructor:Person,
   age:21,
  sayName(){
       console.log(`Name is ${this.name}`);
  }
}
let person1=new Person('John'); 
console.log(person1 instanceof Person); //returns true
console.log(person1.constructor===Person); //returns true
console.log(Person.prototype.isPrototypeOf(person1)); //returns true

My question is:
Whats the difference among these three, since they seem to achieve the same thing?

2 Likes
  • instanceof is a keyword, x instanceof y, returns true or false. It is asking whether an object is an instance 9f another object - eg you have a class, and you create an instance of it.
  • x.constructor is a property on an object, its value is a function, the actual constructor function used to create the object. Eg you have an instance of a class, and its constructor property is the actual constructor used for the class.
  • x.prototypeOf(y) is a function that returns true or false depending on whether x is a prototype of y. On your case you are checking if the prototype of an instance is the prototype of a class.

In your case, they all return the same thing because you’ve specified that they should return the same thing (eg you’ve said person1.constructor === Person), they aren’t actually doing the same thing by themselves.

3 Likes