JS: instanceof Operator
obj instanceof f
-
- Return
true
if obj is a child (or child of child etc) off.prototype
. - obj must be a Object Type.
- f must be a function type.
- Return
γ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β
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);
// 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, see Determine Type of Object
- If you want to determine if a object is in the Prototype Chain of another, use Object.prototype.isPrototypeOf
- Don't use property key
"constructor"
. γsee Property Key "constructor"γ
JavaScript, Constructor, Class
- JS: this Binding
- JS: What is Constructor
- JS: Property Key "prototype"
- JS: Operator βnewβ
- JS: instanceof Operator
- JS: Property Key "constructor"
- JS: Difference Between typeof, instanceof, constructor property
- JS: Class
- JS: Class Syntax
- JS: Class Expression
- JS: typeof Class
- JS: Keyword βstaticβ (static method)
- JS: Keyword βextendsβ
- JS: Keyword βsuperβ
- JS: Define a Class Without Using Keyword class