JS: instanceof (operator)

By Xah Lee. Date: . Last updated: .
obj instanceof f
  • Return true if obj is a child (or child of child etc) of f.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);
// 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);

JavaScript. Constructor, Class