Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's thedifference between comparing object.constructor to its constructor and instanceof? [duplicate]

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.

like image 853
Tal Arbatov Avatar asked Jul 11 '18 17:07

Tal Arbatov


People also ask

What is the difference between object and constructor?

A constructor, as its name suggests, is designed to create and set up multiple instances of an object. An object literal on the other hand is one-off, like string and number literals, and used more often as configuration objects or global singletons (e.g. for namespacing).

What is object constructor in JavaScript?

Object() constructor The Object constructor turns the input into an object. Its behavior depends on the input's type. If the value is null or undefined , it creates and returns an empty object. Otherwise, it returns an object of a Type that corresponds to the given value.

Can JavaScript class have multiple constructors?

Definition and Usage Note: A class cannot have more than one constructor() method. This will throw a SyntaxError .

Why do we use constructor in OOP?

A constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!


1 Answers

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.

like image 168
mccambridge Avatar answered Oct 04 '22 02:10

mccambridge