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.

[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);

JavaScript, Constructor, Class

BUY Ξ£JS JavaScript in Depth