es6对象代理

代理模式(英语:Proxy Pattern)是程序设计中的一种设计模式。

所谓的代理者是指一个类别可以作为其它东西的接口。代理者可以作任何东西的接口:网络连接、内存中的大对象、文件或其它昂贵或无法复制的资源。

{
    let Person = {
    name:'es6',
    sex:'male',
    age:12
 };
    
let person = new Proxy(Person,
    {
        // target是代理的数据即Person,value是要操作的那个属性
        get(target,value){
            return target[value];
        },
        // target是代理的数据即Person,key是要操作的属性,value是属性的值
        set(target,key,value){
            if(key !== 'sex')
                target[key] = value;
        }
    });
console.table({
    name:person.name,
    sex:person.sex,
    age:person.age
});

try{
    person.sex = 'female';
}catch(e){
    console.log(e);
}finally{

}
}

猜你喜欢

转载自blog.csdn.net/lishundi/article/details/81668686