先看官方的解释
// 代码块演示
// Symbol写入私有化变量
const cache = {
name: '西瓜',
private: Symbol(),
set showInfo(v) {
if (!Number.isInteger(v)) throw new Error('传入整数');
this[this.private] = v;
},
get showInfo() {
return `${
this.name}有${
this[this.private]}个`;
}
};
cache.showInfo = 123;
console.log(cache);
//{name: '西瓜', private: Symbol(), showInfo: [Getter/Setter], [Symbol()]: 123}
console.log(cache.showInfo);
// 西瓜有123个
// 注意点
在对象初始化时 设置set || get 关键字时 所指定的为函数;
在访问set || get指向的方法时 以该对象内所申明的函数名作为键名
get 方法传递参数会抛出错误
下面延伸当设置set || get后对象合并带来的问题
基于上方代码下面进行补充
// 合并对象cache
const cache1 = Object.assign({
}, cache);
cache1.showInfo = 456;
console.log(cache1);
// { name: '西瓜', private: Symbol(), showInfo: '西瓜有123个', [Symbol()]: 123 }
console.log(cache1.showInfo);
// 456
理想效果是 合并数据后 修改showInfor值为456并输出 西瓜有456个
但可以看到Object.assign()将showInfor作为了一个普通属性进行合并
故此在下方对数据进行处理时 也只是修改该属性值
解决方法
// 使用 Object.getOwnPropertyDescriptors 获取对象属性描述信息
// 利用 Object.defineProperties 处理属性描述信息 完成对象set get方法拷贝
const cache1 = Object.defineProperties({
}, Object.getOwnPropertyDescriptors(cache));
console.log(cache1);
//{name: '西瓜', private: Symbol(), showInfo: [Getter/Setter], [Symbol()]: 123}
cache1.showInfo = 789;
console.log(cache1.showInfo);// 西瓜有789个