The instanceof operator

Parent Previous Next

Intro

Objects

The prototype

hasOwnProperty

Functions

How this works

Closures and references

The arguments object

Scopes and namespaces

Constructors

Equality and comparisons

Arrays

The Array constructor

The for in loop

The typeof operator

The instanceof operator

Type casting

undefined and null

Reasons against eval

setTimeout and setInterval

Automatic semicolon insertion

The instanceof operator #top

The instanceof operator compares the constructors of its two operands. It is only useful when comparing custom made objects. Used on built-in types, it is nearly as useless as the typeof operator.

Comparing custom objects

function Foo() {}
function Bar() {}
Bar.prototype = new Foo();
new Bar() instanceof Bar; // true
new Bar() instanceof Foo; // true
// This just sets Bar.prototype to the function object Foo
// But not to an actual instance of Foo
Bar.prototype = Foo;
new Bar() instanceof Foo; // false

Using instanceof with native types

new String('foo') instanceof String; // true
new String('foo') instanceof Object; // true
'foo' instanceof String; // false
'foo' instanceof Object; // false

One important thing to note here is, that instanceof does not work on objects that origin from different JavaScript contexts (e.g. different documents in a web browser), since their constructors will not be the exact same object.

In conclusion

The instanceof operator should only be used when dealing with custom made objects that origin from the same JavaScript context. Just like the typeof operator, every other use of it should be avoided.

Created with the Personal Edition of HelpNDoc: Easily create HTML Help documents