views:

2265

answers:

3

What is the instanceof operator in JavaScript?

I saw this in a blog post by John Resig, and didn't understand what does it means in regular JavaScript code (without that library).

+6  A: 

Checks the current object and returns true if the object is of the specified object type.

Here are some good examples: http://www.herongyang.com/JavaScript/Prototype-instanceof-Operator-Determine-Object-Type.html

Here is an example taken directly from Mozilla's dev site:

var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)

Added example and explanation when you declare a variable you give it a specific type. For instance:

int i;
float f;
Customer c;

This could be for any language not just javascript. So what instanceof does is it checks the object to see if it is of the type specified so above we could do:

c instanceof Customer; //returns true as c is just a customer
c instanceof String; //returns false as c is not a string, its a customer silly!
JonH
@Alon - I added an example for you. See above, color1 is of type string, so when you say `color1 instanceof String;` this will return true because color1 is a string.
JonH
@Alon - It checks an object to see what type of object it is. Consider a person / customer object. So `person p = new person()` p is now a person type and not a string type.
JonH
A: 
//Vehicle is a function. But by naming conventions
//(first letter is uppercase), it is also an object
//constructor function ("class").
function Vehicle(numWheels) {
    this.numWheels = numWheels;
}

//We can create new instances and check their types.
myRoadster = new Vehicle(4);
alert(myRoadster instanceof Vehicle);
Justice