What’s the JavaScript’s Object.prototype behavior?

Explanation

So first, your two lines of code create a function, obj, and assign to it’s prototype {x: 5}.

When you create an instance of this object, it seems to have an internal reference to the prototype that existed when it was new‘d.

After this, you reassign the prototype to {y: 6} which does not affect the instance1 internal reference to the first prototype.

Then when you create instance2 it has an internal reference to the 2nd prototype and therefore, logging them will produce 5, undefined, undefined, 6.

#4

You could, rather than reassign the prototype to a new object:

obj.prototype = {y: 6};

Modify the prototype instead:

delete obj.prototype.x; // Setting to undefined should produce same behaviour
obj.prototype.y = 6;

This will produce the output: undefined, 6, undefined, 6

I have tested this with http://jsfiddle.net/9j3260gp/ on Chrome and Firefox latest versions on Windows.

Leave a Comment