0

I want to know if is there any difference between these two methods of checking whether an object is an instance of a class/constructor. I searched about it and found these two ways.

obj instanceof SomeConstructor

obj.constructor === SomeConstructor

So my questions are: Is there any difference between the two?

Which one is a better practice?

Also, Is there any other way better than these two?

Rohit Agrawal
  • 1,496
  • 9
  • 20
  • Possible duplicate of [Difference between instanceof and constructor property](https://stackoverflow.com/questions/18172902/difference-between-instanceof-and-constructor-property) – Dane Nov 15 '17 at 06:25
  • An object can be an *instanceOf* many constructors. It can only return one *constructor* property value, which may not point to any of the objects for which *instanceOf* returns true. – RobG Nov 15 '17 at 06:36
  • @Dane sir that question answers only one of my 3 queries. So I think it shouldn't be a duplicate. – Rohit Agrawal Nov 15 '17 at 06:39
  • @RohitAgrawal—in a way it answers the second, since they not directly comparable you can't really evaluate "better" without some criteria to make an evaluation. ;-) – RobG Nov 15 '17 at 06:48

2 Answers2

1

Found this on web,

instanceof

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

constructor

Returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name.

Reference

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor

Nisal Edu
  • 7,237
  • 4
  • 28
  • 34
  • 1
    And the other 2 questions? ;-) Also, the second definition is not necessarily correct. An object's inherited *constructor* property can be set to any value. – RobG Nov 15 '17 at 06:30
0

As per the explanation of @Nisal Edu there, the instanceof is carrying prototype exists into the object chain else return false. obj.constructor === Object is necessary value for every object this return true.

It's mean

obj.constructor === Object // always return true
obj instanceof Object //return false if prototype is nowhere in object's prototype chain
A.D.
  • 2,352
  • 2
  • 15
  • 25