The instanceof
keyword in JavaScript can be quite confusing when it is first encountered, as people tend to think that JavaScript is not an object-oriented programming language.
- What is it?
- What problems does it solve?
- When is it appropriate and when not?
instanceof
is just syntactic sugar forisPrototypeOf
:instanceof
just depends on the prototype of a constructor of an object.A constructor is just a normal function. Strictly speaking it is a function object, since everything is an object in Javascript. And this function object has a prototype, because every function has a prototype.
A prototype is just a normal object, which is located within the prototype chain of another object. That means being in the prototype chain of another object makes an object to a prototype:
The
instanceof
operator should be avoided because it fakes classes, which do not exist in Javascript. Despite theclass
keyword not in ES2015 either, sinceclass
is again just syntactic sugar for...but that's another story.Javascript is a prototypal language which means it uses prototypes for 'inheritance'. the
instanceof
operator tests if a constructor function'sprototype
propertype is present in the__proto__
chain of an object. This means that it will do the following (assuming that testObj is a function object):obj.__proto__ === testObj.prototype
>> if this istrue
instanceof
will returntrue
.obj.__proto__.__proto__ === testObj.prototype
>> if this istrue
instanceof
will returntrue
.testObj.prototype
theninstanceof
operator will returnfalse
.Example:
It solved the problem of conveniently checking if an object derives from a certain prototype. For example, when a function recieves an object which can have various prototypes. Then, before using methods from the prototype chain, we can use the
instanceof
operator to check whether the these methods are on the object.Example:
Here in the
talk()
function first is checked if the prototype is located on the object. After this the appropriate method is picked to execute. Not doing this check could result in executing a method which doesn't exist and thus a reference error.We kind of already went over this. Use it when you are in need of checking the prototype of an object before doing something with it.
And you can use it for error handling and debugging, like this:
There's an important facet to instanceof that does not seem to be covered in any of the comments thus far: inheritance. A variable being evaluated by use of instanceof could return true for multiple "types" due to prototypal inheritance.
For example, let's define a type and a subtype:
Now that we have a couple of "classes" lets make some instances, and find out what they're instances of:
See that last line? All "new" calls to a function return an object that inherits from Object. This holds true even when using object creation shorthand:
And what about the "class" definitions themselves? What are they instances of?
I feel that understanding that any object can be an instance of MULTIPLE types is important, since you my (incorrectly) assume that you could differentiate between, say and object and a function by use of
instanceof
. As this last example clearly shows a function is an object.This is also important if you are using any inheritance patterns and want to confirm the progeny of an object by methods other than duck-typing.
Hope that helps anyone exploring
instanceof
.instanceof
The Left Hand Side (LHS) operand is the actual object being tested to the Right Hand Side (RHS) operand which is the actual constructor of a class. The basic definition is:
Here are some good examples and here is an example taken directly from Mozilla's developer site:
One thing worth mentioning is
instanceof
evaluates to true if the object inherits from the classe's prototype:That is
p instanceof Person
is true sincep
inherits fromPerson.prototype
.Per the OP's request
I've added a small example with some sample code and an explanation.
When you declare a variable you give it a specific type.
For instance:
The above show you some variables, namely
i
,f
, andc
. The types areinteger
,float
and a user definedCustomer
data type. Types such as the above could be for any language, not just JavaScript. However, with JavaScript when you declare a variable you don't explicitly define a type,var x
, x could be a number / string / a user defined data type. So whatinstanceof
does is it checks the object to see if it is of the type specified so from above taking theCustomer
object we could do:Above we've seen that
c
was declared with the typeCustomer
. We've new'd it and checked whether it is of typeCustomer
or not. Sure is, it returns true. Then still using theCustomer
object we check if it is aString
. Nope, definitely not aString
we newed aCustomer
object not aString
object. In this case, it returns false.It really is that simple!
The other answers here are correct, but they don't get into how
instanceof
actually works, which may be of interest to some language lawyers out there.Every object in JavaScript has a prototype, accessible through the
__proto__
property. Functions also have aprototype
property, which is the initial__proto__
for any objects created by them. When a function is created, it is given a unique object forprototype
. Theinstanceof
operator uses this uniqueness to give you an answer. Here's whatinstanceof
might look like if you wrote it as a function.This is basically paraphrasing ECMA-262 edition 5.1 (also known as ES5), section 15.3.5.3.
Note that you can reassign any object to a function's
prototype
property, and you can reassign an object's__proto__
property after it is constructed. This will give you some interesting results: