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:
  1. function Abhi() { }  
  2. var abhijeet = new Abhi  
  3. 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:
  1. function Abhi() { }  
  2. var abhijeet = new Abhi  
  3. 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.