首页 > 解决方案 > 使用 Object.freeze(Class.prototype) 同时保持能够覆盖原型属性

问题描述

如果为某个类的实例分配了与类原型中的名称冲突的属性,则将其分配给实例(对原型没有影响),并且任何尝试访问实例上的该属性现在都会导致实例的属性,而不是原型的:

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

奇怪的是,Object.freeze(Class.prototype)会干扰实例属性的更改:

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!

这对我来说是不受欢迎的行为。

我有什么方法可以冻结原型,但保持覆盖实例上的原型属性的能力?

标签: javascriptprototype

解决方案


推荐阅读