Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : Modifying Prototype doesn't affect existing Instances [duplicate]

I created 2 instances of a prototype, changed a function in prototype, changes reflected in both the instances (Great). However, when I modified the prototype by removing the function, the function still existed for the existing instances.

function A() {
  this.name = "cool";
}

A.prototype = {
  howCool: function() {
    return this.name + "er";
  }
};

var a1 = new A(),
  a2 = new A();

a1.name = "hot";
//line1
console.log(a1.howCool());
//line2
console.log(a2.howCool());

A.prototype = {};

//line3
console.log(a1.howCool());

//line4
var a3 = new A();
console.log(a3.howCool());

Line 1 and 2 are working as expected and after setting the protoype back to empty, line 4 is showing undefined which is expected. line 3 however is still showing the function definition.

like image 993
Siddharth Mutluru Avatar asked May 03 '17 16:05

Siddharth Mutluru


1 Answers

Essentially you're reassigning the prototype property for the function A to point to a new object. This does not affect the old object and thus doesn't affect prior instances.

Here's an illustration of what is happening.

After this code executes:

function A() {
  this.name = "cool";
}

A.prototype = {
  howCool: function() {
    return this.name + "er";
  }
};

var a1 = new A(),
  a2 = new A();

the situation is the following:

before

Then after this code executes:

A.prototype = {};

var a3 = new A();

The A.prototype points to a new object but the [[Prototype]] property for old instances still points to the old object.

after

If you want to actually remove the method, you must edit the original object, not point to a new one.

To actually remove howCool() method from the prototype, something like this would work:

delete A.prototype.howCool

Which would give:

finally

Now any future instances, such as a3, and the prior ones, would all still point to the same object but that object won't have the howCool() method.

like image 106
nem035 Avatar answered Oct 11 '22 23:10

nem035