问题:
如何在ES6
类中优雅地实现受保护的属性?(只能从子类内部访问)
我不是在寻找像“ES没有受保护/包属性”这样的响应。已经知道了。我想要一个漂亮而干净的解决方法来模拟受保护的属性。
我不想增加安全性。只需对所有API
的最终用户公开一个更清晰的接口。
示例:
我有以下API
:(node)
my-class.js:
let Symbols = {
_secret: Symbol("_secret")
};
class MyClass {
constructor() {
this.public = "This is public";
this[Symbols._secret] = "This is private";
}
}
// Set the Symbols to a static propietry so any class can access it and extend it
MyClass[Symbol.for("_Symbols")] = Symbols;
module.exports = MyClass
my-child-class.js:
let MyClass = require("./my-class.js");
// extends protected properties with own properties
Symbols = Object.assign({}, MyClass[Symbol.for("_Symbols")] , {
_childSecret = Symbol("_childSecret")
});
class MyChildClass extends MyClass {
constructor() {
super();
this[Symbols._childSecret] = "This is also private";
console.log(this[Symbols._secret]); //logs "this is private"
console.log(this[Symbols._childSecret]); //logs "this is also private"
}
}
// Set the Symbols to a static propietry so any class can access it and extend it
MyClass[Symbol.for("_Symbols")] = Symbols;
module.exports = MyChildClass;
使用该类:
let MyChildClass = require("./my-child-class.js");
var c = new MyChildClass();
优点:
- 暴露的
API
更加清晰。而且终端用户可以查看所暴露的方法。
问题:
基类中的代码很“好看”,但是子类中的代码不太好看。有没有办法改善顺序?
任何能够访问
Symbol.for("_Symbols")
的人都可以访问 API 的所有受保护/私有属性。(编辑: 我不介意这个。这对我来说不是问题,因为如果有人想要打破 API 访问内部符号,那就是他们的问题。)