如何实现构造函数中`this`中保存的值的隐私?
对于需要保存在this构造函数中的值,我有哪些选择可以实现隐私?例如一个简单的Stack实现:
function Stack(){
this._stack = {}
this._counter = 0
}
Stack.prototype.push = function (item){
this._stack[this._counter++] = item
return this
}
Stack.prototype.pop = function (){
Reflect.deleteProperty(this._stack, --this._counter);
return this
}
Stack.prototype.peek = function (){
return this._stack[this._counter - 1]
}
Stack.prototype.length = function (){
return Object.values(this._stack).length
}
如果这些方法没有定义为原型方法,我可以像这样轻松地私有它们:
function Stack(){
let _stack = {}
let _counter = 0
this.push = function (item){
_stack[_counter++] = item
return this
}
this.pop = function (){
Reflect.deleteProperty(_stack, --_counter);
return this
}
this.peek = function (){
return _stack[_counter - 1]
}
this.length = function (){
return Object.values(_stack).length
}
}
这种方式_stack并_counter没有暴露出来,但是这些方法不在原型链上。
是否有可能实现隐私,而受保护的值保存在this?
回答
这是使用私有字段的示例。您可以使用static关键字将它们设为静态,但这在本示例中不是必需的。
class test {
#lol = 29;
#mas = 15;
constructor() {
this.#lol++;
this.#mas--;
return {
value: this.#lol - this.#mas
};
}
};
console.log(new test().value); // --> 16