6

Lets say I have a Dog constructor

function Dog(name) {
    this.name = name;
}

And I have an instance of that constructor

const myDog = new Dog('Charlie');

As far as I learned recently, there are two ways to check if myDog is an instance of Dog:

1.

console.log(myDog instanceof Dog) //true

2.

console.log(myDog.constructor === Dog) //true

My question is, what are the differences between the two, which one is better and why?

Thanks in advance.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302

1 Answers1

2

The difference is pretty simple. Check out MDN's documentation of instanceOf. If you have an instance Fido that is an instance of GreatDane which is an instance of Dog which is an instance of Object, the following will be the case:

Fido instanceof GreatDane // true
Fido instanceof Dog // true
Fido instanceof Object // true
Fido.constructor === GreatDane // true

However, the following will not be true:

Fido.constructor === Dog // false
Fido.constructor === Object // false

So you can see the instanceOf keyword travels up the lineage, where constructor is looking at the actual function that created your instance.

Neither is better. It depends on your situation. What do you want to know about each object?

As Patrick Roberts points out in the comment below, Fido.constructor would be the actual constructor function inherited from GreatDane. And you are able to modify it, so if you ever changed the constructor, your comparison would then return false.

mccambridge
  • 983
  • 7
  • 16
  • 1
    Not that it would be common-case but one disadvantage of the `constructor` check is that `constructor` is a writable property, so at any point that could be reassigned to an arbitrary value not relating to the object's _actual_ constructor. – Patrick Roberts Jul 11 '18 at 17:26