JavaScript “instanceof” Operator

, , …,

JavaScript has a instanceof operator. It's used like this o instanceof f. The left-hand-side o should be a object. 〔☛ What's Object in JavaScript?〕 The right-hand-side should be a function (that is, typeof returns Function).

o instanceof f returns true when f.prototype is in prototype chain of o.

Here's another way to look at it. o instanceof f is the same as f.prototype.isPrototypeOf(o)


// example showing 「instanceof」 isn't really about constructor. It's about prototype chain

var FF = function () {return Object.create([]);};

var f1 = new FF();

console.log( f1 instanceof FF);              // false
console.log(FF.prototype.isPrototypeOf(f1)); // false

console.log( f1 instanceof Array);              // true
console.log(Array.prototype.isPrototypeOf(f1)); // true

Note: in JavaScript, each object has one parent object (and its parent also has a parent, and so on.). So, any object has a line of parents, called its prototype chain. 〔☛ JavaScript Tutorial: Understanding Prototype & Inheritance

Note: instanceof isn't about constructor, but prototype chain.

ECMAScript §11#sec-11.8.6

blog comments powered by Disqus