The "instanceof" operator

  1. The instanceof operator
  2. When instanceof lies
  3. Summary

The instanceof operator

The instanceof allows to check if the object is created by given constructor:

function Rabbit() { }
var rabbit = new Rabbit

alert(rabbit instanceof Rabbit) // true

The instanceof has nothing to do with the constructor property. 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 example above, the match is found at the first step, because: rabbit.__proto__ == Rabbit.prototype.

A deeper example:

function Rabbit() { }
var rabbit = new Rabbit

alert(rabbit instanceof Object) // true

Here, the match is found at rabbit.__proto__.__proto__ == Object.prototype.

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

When instanceof lies

The instanceof lies when a value comes from another frame or iframe.

For example, an array which came from an iframe is instanceof Array in that iframe. Every frame or iframe has it’s own window object and the hierarchy.

Usually, the problem arises with native objects, so the solution using <a href="/tutorial/type-detection">[Class]] works. It is described in the article [.

Summary

  • obj instanceof Func checks if the obj is a result of new Func. The check is performed by walking the __proto__ chain, so the inheritance is supported:
    var arr = []
    alert(arr instanceof Array) // true
    alert(arr instanceof Object) // true
    
  • The instanceOf lies when an object comes from another window(or frame). The guaranteed-to-work replacement for native objects is checking <a href="/tutorial/type-detection">[Class]], see [.

Tutorial

Donate

Donate to this project