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?
I think it's worth noting that instanceof is defined by the use of the "new" keyword when declaring the object. In the example from JonH;
What he didn't mention is this;
Specifying "new" actually copied the end state of the String constructor function into the color1 var, rather than just setting it to the return value. I think this better shows what the new keyword does;
Using "new" assigns the value of "this" inside the function to the declared var, while not using it assigns the return value instead.
On the question "When is it appropriate and when not?", my 2 cents:
instanceof
is rarely useful in production code, but useful in tests where you want to assert that your code returns / creates objects of the correct types. By being explicit about the kinds of objects your code is returning / creating, your tests become more powerful as a tool for understanding and documenting your code.I just found a real-world application and will use it more often now, I think.
If you use jQuery events, sometimes you want to write a more generic function which may also be called directly (without event). You can use
instanceof
to check if the first parameter of your function is an instance ofjQuery.Event
and react appropriately.In my case, the function needed to calculate something either for all (via click event on a button) or only one specific element. The code I used: