Videos
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:
Checks the current object and returns true if the object is of the specified object type.
Here are some good examples and here is an example taken directly from Mozilla's developer site:
var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral"; //no type specified
color2 instanceof String; // returns false (color2 is not a String object)
One thing worth mentioning is instanceof evaluates to true if the object inherits from the class's prototype:
var p = new Person("Jon");
p instanceof Person
That is p instanceof Person is true since p inherits from Person.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:
int i;
float f;
Customer c;
The above show you some variables, namely i, f, and c. The types are integer, float and a user defined Customer 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 what instanceof does is it checks the object to see if it is of the type specified so from above taking the Customer object we could do:
var c = new Customer();
c instanceof Customer; //Returns true as c is just a customer
c instanceof String; //Returns false as c is not a string, it's a customer silly!
Above we've seen that c was declared with the type Customer. We've new'd it and checked whether it is of type Customer or not. Sure is, it returns true. Then still using the Customer object we check if it is a String. Nope, definitely not a String we newed a Customer object not a String object. In this case, it returns false.
It really is that simple!
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:
function Foo(){ //a Foo constructor
//assign some props
return this;
}
function SubFoo(){ //a SubFoo constructor
Foo.call( this ); //inherit static props
//assign some new props
return this;
}
SubFoo.prototype = Object.create(Foo.prototype); // Inherit prototype
SubFoo.prototype.constructor = SubFoo;
Now that we have a couple of "classes" lets make some instances, and find out what they're instances of:
var
foo = new Foo()
, subfoo = new SubFoo()
;
alert(
"Q: Is foo an instance of Foo? "
+ "A: " + ( foo instanceof Foo )
); // -> true
alert(
"Q: Is foo an instance of SubFoo? "
+ "A: " + ( foo instanceof SubFoo )
); // -> false
alert(
"Q: Is subfoo an instance of Foo? "
+ "A: " + ( subfoo instanceof Foo )
); // -> true
alert(
"Q: Is subfoo an instance of SubFoo? "
+ "A: " + ( subfoo instanceof SubFoo )
); // -> true
alert(
"Q: Is subfoo an instance of Object? "
+ "A: " + ( subfoo instanceof Object )
); // -> true
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:
alert(
"Q: Is {} an instance of Object? "
+ "A: " + ( {} instanceof Object )
); // -> true
And what about the "class" definitions themselves? What are they instances of?
alert(
"Q: Is Foo an instance of Object? "
+ "A:" + ( Foo instanceof Object)
); // -> true
alert(
"Q: Is Foo an instance of Function? "
+ "A:" + ( Foo instanceof Function)
); // -> true
I feel that understanding that any object can be an instance of MULTIPLE types is important, since you may (incorrectly) assume that you could differentiate between, say an 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.
What is the best way to recognize that obj2 and obj3 are different?
That will depend a great deal on what you're doing with them. One way would be to use instanceof Obj2 and instanceof Obj3. Since both objects were created with Obj1.prototype in their prototype chain, it makes sense that they identify as being an instance of what we would call the supertype in class-based OOP.
How does actually instanceof work?
The short version
obj instanceof F looks to see if the object referenced by F.prototype is anywhere in obj's prototype chain. It doesn't use constructor at all.
More details
This is covered in the spec by §11.8.5 - The instanceof Operator, which says (indirectly, via §8.6.2) that it calls the [[HasInstance]] internal method of the function object, passing in the object we're testing. Function's [[HasInstance]] (in §15.3.5.3) says that it gets the object reference from the function's prototype property and then returns true if that object is anywhere in the target object's prototype chain, false if it doesn't.
It doesn't use constructor (nothing in JavaScript itself does, in fact) — and if you think about it, it can't, because an object's constructor property can only point at one function, but an object can be instanceof multiple functions — for instance, in the case of pseudo-classical inheritance:
function F1() {}
function F2() {
F1.call(this);
}
F2.prototype = Object.create(F1.prototype);
F2.prototype.constructor = F2;
var obj = new F2();
console.log(obj instanceof F1); // true
console.log(obj instanceof F2); // true
Both are true because the two objects referenced by F1.prototype and F2.prototype are both in obj's prototype chain.
instanceof being true doesn't necessarily mean that obj was created by a call to F, either directly or indirectly; it just indicates there's a vague link between them (F.prototype refers to an object that's also in obj's prototype chain). It usually means F was involved in creating the object, but there's no guarantee.
For instance:
function F() {}
var obj = Object.create(F.prototype);
console.log(obj instanceof F); // true
Note that F wasn't called to create the object, at all.
Or perhaps more clearly and/or dramatically:
function F() {}
var p = {};
var obj = Object.create(p);
console.log(obj instanceof F); // false
F.prototype = p;
console.log(obj instanceof F); // true
There's also this unusual, but entirely possible, version:
function F1() {}
function F2() {}
F1.prototype = F2.prototype = {};
var obj = new F1();
console.log(obj instanceof F2); // true
Or this one:
function F1() {}
function F2() {}
var obj = new F2();
console.log(obj instanceof F1); // false
F1.prototype = F2.prototype;
console.log(obj instanceof F1); // true
Most simply: obj instanceof constructor yields true when obj has constructor's prototype in it's constructor/prototype chain. In other words, your asking your engine whether obj can be treated like an instance of constructor / whether obj behaves like a constructor object.
There is a small handful of syntaxes that allow you to put constructor's prototype in obj's prototype chain. Any and all of them will cause obj instanceof constructor to be true. In your examples, both obj2 and obj3 have Obj1 in their prototype chain.
So, when you ask your javascript engine whether either obj2 or obj3 behave like an instance of Obj1, JavaScript assumes true -- the only case wherein they wouldn't is if you've overridden Obj1's behavior down the line.
The ECMAScript 262 specification will tell you this. Quoting directly from its The `instanceof operator section:
11.8.6 The instanceof operator
The production RelationalExpression : RelationalExpression instanceof ShiftExpression is evaluated as follows:
- Let lref be the result of evaluating RelationalExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating ShiftExpression.
- Let rval be GetValue(rref).
- If Type(rval) is not Object, throw a TypeError exception.
- If rval does not have a [[HasInstance]] internal method, throw a TypeError exception.
- Return the result of calling the [[HasInstance]] internal method of rval with argument lval.
As for what [[HasInstance]] is, the specification also defines that in its Object Internal Properties and Methods section as:
[[HasInstance]]
Returns a Boolean value indicating whether the argument is likely an Object that was constructed by this object. Of the standard built-in ECMAScript objects, only Function objects implement [[HasInstance]]
Further reading on this: http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.4.5.3
This link states:
The instanceof operator tests presence of constructor.prototype in object's prototype chain.