Open Hongbusi opened 2 years ago
(function privateProxyProducer() {
const privateValue = new Map();
const ErrorMap = {
normal: 'PrivateProxyProducer Error: 未查询到相关信息'
};
function errorHandler(mode = 'normal') {
return ErrorMap[mode];
}
return function () {
this.getName = (key) => {
return privateValue.has(key) ? privateValue.get(key) : errorHandler();
};
this.setName = (key, value) => {
return key && privateValue.set(key, value) && true;
};
this.hasName = (key) => {
return key && privateValue.has(key)
}
};
})()();
setName('hi', false);
const res1 = getName('hi2');
console.log(res1);
const a = { age: 1 };
setName(a, 'another');
const res2 = getName(a);
console.log(res2);
// 函数实现
function private(){
let a = '我是私有变量';
this.getName=function(){
return a;
}
}
const p = new private()
console.log(p.a)
console.log(p.getName())
// class 实现
class private1 {
constructor() {
let a = '我是私有变量';
this.getName = function () {
return a;
};
}
}
const p1 = new private1()
console.log(p1.a)
console.log(p1.getName())
通过函数的创建形式:
另外在这里讲一下网上一种错误的实现方案,通过配置 defineProperty 的不可枚举,不可修改:
配置不可枚举只是让某个属性不能通过
for..in
或Object.keys()
的方式遍历出来,直接user.name
一样还是可以访问到这个属性。