The "instanceof" operator in JavaScript

The "instanceof" operator in JavaScript

The instanceof allows to check if the object has been created by the given constructor or not:

For example:

function Abhi() { }
var abhijeet = new Abhi
alert(abhijeet instanceof Abhi) // true

It follows the __proto__ chain instead.

The logic behind obj instanceof F:

1. Get obj.__proto__
2. Compare obj.__proto__ against F.prototype
3. If no match then set temporarily obj = obj.__proto__ and repeat step 2 until either match is found or the chain ends.

In the above example, the match is found at the first step,

because: abhijeet.__proto__ == Abhi.prototype

Another example:

function Abhi() { }
var abhijeet = new Abhi
alert(abhijeet instanceof Object) // true

Here we can see that the match is found at abhijeet.__proto__.__proto__ == Object.prototype.

Note that the comparison only uses __proto__ and prototype, the function object itself isn’t involved.

Ebook Download
View all
Learn
View all