Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why resetting prototype does not remove the property from objects?

Im trying to get my head around javascript prototyping & possible inheritance, but I'm certainly missing something. Let's start with simple constructor (function Counter()), adding simple property and instantiation of object:

function Counter() { this.a = "first"; };
Counter.prototype.b = "second";
var counter = new Counter();

At this point, counter.a returns "first", counter.b returns "second" and counter.c is of course undefined which is all understandable. Let's add another property to constructor's prototype:

Counter.prototype.c = "third";  

Right now, counter.c would return "third". But... we've changed our mind, lets get rid of those properties:

Counter.prototype = {};

Using simple logic, while overwriting counter prototype's prototype property, we would lose the properties for counter which we've added before to Counter.prototype. But that's not the case - counter.c Returns "third". I am lost here. So... let's try overwriting the value:

Counter.prototype.c = "fourth hohoho";

Nothing changes, counter.c still returns "third".

Why did it not succeed to remove the properties? What am I missing?

like image 864
mrówa Avatar asked May 22 '13 14:05

mrówa


2 Answers

When you create your object, a reference to its prototype object is added to the prototype.

You can augment that prototype object, and because the instances share the reference, those changes will be reflected in any existing instances.

However if you overwrite the prototype object, the previously created instances still hold a reference to the original prototype object.

It's the same as what happens with this code:

var a = {};
var b = a;

a.foo = 'bar';    // augment 'a'
b.foo === 'bar';  // true

a = {};           // overwrite 'a'
b.foo === 'bar';  // still true
like image 177
Alnitak Avatar answered Oct 06 '22 07:10

Alnitak


You can add/remove properties from a prototype object dynamically, but you can't replace the prototype object of instances that have been already been created. In your example, instances created after you replaced the constructor's prototype property will get the new prototype, but the ones created before that will keep a reference to the former object.

If you want to clear some property from the prototype, remove them from the original object, using the delete operator:

delete Counter.prototype.c;
like image 31
bfavaretto Avatar answered Oct 06 '22 07:10

bfavaretto