- Continued
Anytime a constructor function creates a new object, that object is said to be an instance of its constructor. JavaScript gives a convenient way to verify this with the
instanceof
operator.instanceof
allows you to compare an object to a constructor, returningtrue
orfalse
based on whether or not that object was created with the constructor.Here's an example:
function Dog(name, color) {
this.name = name;
this.color = color;
this.numLegs = 4;
}
let goldenRetriever = new Dog("Naruto", orange);
goldenRetriever instanceof Dog; // will display true
- This
instanceof
method would returntrue
. - If an object is created without using a constructor,
instanceof
will verify that it is not an instance of that constructor:
Top comments (1)
Shouldn't
goldenRetriever instanceof House;
returnfalse
?Some comments have been hidden by the post's author - find out more