设计思路
- 访问控制:
- 使用WeakMap来实现对父类私有属性的保护。WeakMap的键是对象,且键所指向的对象若没有其他引用,会被垃圾回收机制回收,从而保证私有性。
- 对于方法,可以通过闭包的方式将其封装在内部,只暴露需要公开的方法。
- 防止恶意篡改原型:
- 使用
Object.freeze()
方法冻结原型对象,防止在运行时对原型进行修改。
- 可扩展性:
- 通过在类的构造函数和原型方法中预留扩展点(例如钩子函数),以便在子类中可以安全地添加新功能,而不破坏已有的安全机制。
关键代码示例
// 父类
class Parent {
constructor() {
const privateData = new WeakMap();
privateData.set(this, {
secret: 'This is a secret'
});
this.getSecret = () => privateData.get(this).secret;
}
}
// 子类
class Child extends Parent {
constructor() {
super();
// 子类构造函数中的扩展点,可安全添加新功能
this.newFeature = 'This is a new feature';
}
// 子类可重写父类方法,但需遵循安全机制
getSecret() {
// 调用父类方法获取秘密
const secret = super.getSecret();
return `Enhanced secret: ${secret}`;
}
}
// 防止恶意篡改原型
Object.freeze(Parent.prototype);
Object.freeze(Child.prototype);
// 测试
const child = new Child();
console.log(child.getSecret()); // 输出: Enhanced secret: This is a secret
console.log(child.newFeature); // 输出: This is a new feature
// 尝试修改原型会失败,因为原型已被冻结
// Child.prototype.newMethod = function() {}; // 这行代码会在严格模式下抛出错误,非严格模式下无效