1

If an instance of some class is assigned a property that conflicts with a name in the class' prototype, it is assigned to the instance (having no effect on the prototype), and any attempts to access that property on the instance now result in the instance's property, not the prototype's:

let Class = function() {};
Class.prototype = { z: 'zzz' };

let inst = new Class();
console.log('1:', inst.z); // Initially 'zzz', from prototype

inst.z = 'qqq';
console.log('2:', inst.z); // Now the instance property takes precedence

console.log('3:', Class.prototype); // Prototype did not change

let inst2 = new Class();
console.log('4:', inst2.z); // And of course, other instances are not affected

Strangely, Object.freeze(Class.prototype) interferes with changes to instance properties:

let Class = function() {};
Class.prototype = Object.freeze({ z: 'zzz' });

let inst = new Class();
console.log(inst.z); // From prototype

inst.z = 'qqq'; // No obvious reason why we can't mutate the instance...
console.log(inst.z); // But with Object.freeze, we can't!

This is undesirable behaviour for me.

Is there any way for me to freeze the prototype, but maintain an ability to overwrite prototype properties on the instance?

Gershom Maes
  • 7,358
  • 2
  • 35
  • 55
  • I don't think there's a way to do this. The spec explicitly includes a test on the prototype flags for the given property, and won't allow the value to be updated when it's not writable or extensible on the prototype. – Pointy Jan 13 '21 at 18:58
  • Now, what *might* be good enough would be to explicitly make all the prototype properties not writable *except* for the ones you want to be able to update. – Pointy Jan 13 '21 at 18:59
  • possible duplicate of [Assign new property to empty object which has frozen prototype](https://stackoverflow.com/q/29602584/1048572) – Bergi Jan 13 '21 at 19:00
  • `Object.freeze(Object.defineProperties(Class.prototype, {z: {get(){ return 'zzz'; }, set(v) { Object.defineProperty(this, 'z', {value: v, writable: true, configurable: true}); }}));` – Bergi Jan 13 '21 at 19:02
  • 1
    Good call @Bergi! This is a dup – Gershom Maes Jan 13 '21 at 19:05

0 Answers0