Madhur Parashar
Madhur Parashar

Reputation: 33

Why the object prototype property doesn't override for given code

const object = function() {};
object.prototype = {
  name: 'XYZ'
};
const o = new object();
object.prototype = {
  name: 'PQR'
}
const result = o.name;
console.log(result);

Here the name property doesn't override.

Upvotes: 3

Views: 138

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370639

When you reassign the prototype object, other objects created from that function will not have their internal prototype chains changed unless you explicitly tell Javascript to do so - with good reason, it can be very expensive:

Warning: Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in the Object.setPrototypeOf(...) statement, but may extend to any code that has access to any object whose [[Prototype]] has been altered.

Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using Object.create().

If you have to do so, use Object.setPrototypeOf on an instance, so that its internal prototype points to the new object:

const object = function() {};
object.prototype = {
  name: 'XYZ'
};
const o = new object();
object.prototype = {
  name: 'PQR'
}
Object.setPrototypeOf(o, object.prototype);

const result = o.name;
console.log(result);

But this should hopefully only be done for the sake of a theoretical exercise. There's no reason to do this in actual code meant to accomplish a concrete task.

Upvotes: 5

Related Questions