1

I am just playing with the instanceof operator. I want to know whether my understanding is correct or not

var C = function(){};
// in the above statement C has a "prototype" property which points to an object which has 
// the constructor property which points to C constructor
var o1 = new C();
// in above statement o1.__proto__ is points to C.prototype. that means inheriting from C.prototype.
console.log(o1 instanceof C) // returns true
//instanceof will check o1.__proto__ is equals to C.prototype(recursively until it finds null object).
C.prototype = {};
console.log(o1 instanceof C) // false;
in the above case o1 was inherited from C.prototype which points to the different object not the present C.prototype object (empty object). so the instanceof condition check fails hence its false.

please tell me if my interpretation is wrong

1
  • 1
    Your understanding seems correct. Commented Mar 18, 2013 at 20:07

1 Answer 1

3

Yes, instanceof checks the constructors in the prototype chain of an object and returns true if the passed constructor is found anywhere in the chain. So if you destroy the prototype of a function, as you do by overwriting it with an empty object, then instanceof will always return false.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.