javascript - 使用 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!
这对我来说是不受欢迎的行为。
我有什么方法可以冻结原型,但保持覆盖实例上的原型属性的能力?
解决方案
推荐阅读
- swift - 冒号(:) 和 eqaul 到运算符(==)之间的区别 - 通用 Where 子句:我希望 Array 有条件地符合协议
- javascript - 尝试使用javascript函数在用户单击php时在特定时间运行mysql查询
- javascript - 使用 Lodash _.get 返回多个元素?
- reactjs - 升级到 mobx-react@6.0.0 会导致死循环
- angular - 订阅错误:类型 'void'.ts(2339) 上不存在属性 'subscribe'
- android - “如何将字符串生成器转换为数组?”
- android - 如果调用了 firebaseAuth.signOut() si,则无法发送用户数据
- java - KeyEvent更改照片不起作用,如何激活它?
- azure - Azure kubernetes 部署错误 - 0/1 个节点可用:1 个节点与节点选择器不匹配
- python-3.6 - 如何在 POS odoo 11 中为我的自定义按钮添加功能打印收据?