JS: instanceof (operator)
obj instanceof f-
- Return
trueif obj is a child (or child of child etc) off.prototype. - obj must be a Object Type.
- f must be a function type.
basically the same as
f.prototype.isPrototypeOf(obj)// typical way of using instanceof function Xcon() { this.p = 3; } const xobj = new Xcon(); console.assert((xobj instanceof Xcon) === true); - Return
// shows how (x instanceof f) is same as ((f.prototype).isPrototypeOf(x)) const xgen0 = {}; const xgen1 = {}; const xgen2 = {}; // setup parent chain Reflect.setPrototypeOf(xgen1, xgen0); Reflect.setPrototypeOf(xgen2, xgen1); // define a function function Xcon() {} // set the property key prototype Xcon.prototype = xgen0; console.assert((xgen2 instanceof Xcon) === true); console.assert(Reflect.apply(Object.prototype.isPrototypeOf, Xcon.prototype, [xgen2]) === 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 Xcon function Xcon() { return {}; // returns a object } // create a instance const xobj = new Xcon(); console.assert((xobj instanceof Xcon) === false);
// example of instanceof with unexpected result // create a constructor function Xcon function Xcon() { this.p = 3; } // create a instance const xobj = new Xcon(); // change the value of property key "prototype" Xcon.prototype = []; console.assert((xobj instanceof Xcon) === 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 constructor (property)〕
JavaScript. Constructor, Class
- JS: Constructor and Class
- JS: this (binding)
- JS: Constructor
- JS: prototype (property)
- JS: new (operator)
- JS: instanceof (operator)
- JS: constructor (property)
- JS: typeof, instanceof, .constructor
- JS: class (keyword)
- JS: Class Expression
- JS: typeof Class
- JS: static (keyword)
- JS: extends (keyword)
- JS: super (keyword)
- JS: Define a Class Without class