3

I am very new to JavaScript and could not understand the code below (code source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof)

// defining constructors
function C(){}
function D(){}

var o = new C();

// true, because: Object.getPrototypeOf(o) === C.prototype
o instanceof C;

// false, because D.prototype is nowhere in o's prototype chain
o instanceof D;

o instanceof Object; // true, because:
C.prototype instanceof Object // true

C.prototype = {};
var o2 = new C();

o2 instanceof C; // true

// false, because C.prototype is nowhere in
// o's prototype chain anymore
o instanceof C; 

Why in the last line "o instanceof C" returns false? I don't understand how "C.prototype = {}" removes "C.prototype" from o's prototype chain. thank you!

1
  • C.prototype does indeed replace the entire prototype. If you want to extend prototype chain, just add things onto C.prototype, but don't replace the whole thing. Commented Apr 13, 2015 at 20:57

1 Answer 1

3

When an object is created, a link to the prototype is placed on the object itself. When the "prototype" property of the constructor is updated, then subsequently-constructed objects will reference that new object, while the old ones still reference the old prototype object. Since that object is no longer associated with the constructor function, the instanceof test fails.

The prototype object on the constructor can be changed internally as desired without breaking the instanceof relationship. That is, properties can be added or removed, and property values can be changed.

In modern JavaScript environments, the Object.getPrototypeOf() method can be used to retrieve the prototype object of an instantiated object.

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.