JavaScript 对象object中set(setter)和get(getter)使用,分析以及setter/getter拷贝

先看官方的解释
在这里插入图片描述
在这里插入图片描述

// 代码块演示

// 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个

猜你喜欢

转载自blog.csdn.net/qq_45284938/article/details/127262560