JavaScript: instanceof Operator
obj instanceof f
-
Return
true
if obj is a child (or child of child …) off.prototype
.
obj must be a Object Type.
f must be a function type.
[see Prototype and Inheritance]
obj instanceof f
is basically the same as f.prototype.isPrototypeOf(obj)
.
[see Object.prototype.isPrototypeOf]
// shows how (x instanceof f) is same as ((f.prototype).isPrototypeOf(x)) const xx0 = {}; const xx1 = {}; const xx2 = {}; // setup parent chain Reflect.setPrototypeOf(xx0, null); Reflect.setPrototypeOf(xx1, xx0); Reflect.setPrototypeOf(xx2, xx1); // define a function function ff() {} // set the property key prototype ff.prototype = xx0; console.log((xx2 instanceof ff) === true); console.log( Reflect.apply(Object.prototype.isPrototypeOf, ff.prototype, [xx2]) === true, );
Here is a typical use of instanceof
:
// common way of using instanceof function FF() { this.p = 3; } const f1 = new FF(); console.log((f1 instanceof FF) === true); console.log(FF.prototype.isPrototypeOf(f1) === true);
Tip: Don't Use “instanceof”
Tip: Avoid using the instanceof
operator, because it is not a reliable way to find a object's constructor or type.
(there's no reliable way to find a object's constructor. Objects are often created without constructor, and object's parent can be changed anytime.)
Here is examples where instanceof
returns unexpected result.
// example showing instanceof isn't really about constructor. It's about prototype chain // create a constructor function FF function FF() { return {}; } // returns a object // create a instance const f1 = new FF(); console.log((f1 instanceof FF) === false); console.log(FF.prototype.isPrototypeOf(f1) === false);
// example of instanceof with unexpected result // create a constructor function FF function FF() { this.p = 3; } // create a instance const f1 = new FF(); // change property "prototype" FF.prototype = []; console.log((f1 instanceof FF) === false);
If you want to find the subtype of a object, use
Object.prototype.toString.call(obj)
[see Determine Type of Object]
If you want to determine if a object is in the Prototype Chain of another, use isPrototypeOf
.
[see Object.prototype.isPrototypeOf]
Don't use property key "constructor"
.
[see Property Key “constructor”]