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.
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).
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.
Definition and Usage Note: A class cannot have more than one constructor() method. This will throw a SyntaxError .
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 (__)!
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With