The instanceof operator |
||
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.
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
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.
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