美文网首页
ES6 6.Proxy和Reflect

ES6 6.Proxy和Reflect

作者: Coldhands | 来源:发表于2018-07-20 23:44 被阅读0次

    Proxy

    {
        let obj = {
            time: '2018-01-01',
            name: '玲珑',
            _r: 123
        }
        let monitor = new Proxy(obj,{
            //拦截对象属性的读取
            get(target,key){
                return target[key].replace('2018','2019');
            },
            //拦截对象属性
            set(target,key,value){
                if(key === 'name'){
                    return target[key] = value;
                }else{
                    return target[key];
                }
            },
            // 拦截delete
            deleteProperty(target,key){
                if(key.indexOf('_')>-1){
                    delete target[key];
                    return true;
                }else{
                    return target[key];
                }
            },
            // 拦截    Object.keys,Object.getOwnPropertySymbols,Object.getOwnPropertyNames
            ownKeys(target){
                return Object.keys(target).filter(item=>item!='time')
            }
        })
        monitor.time = '2019';
        monitor.name = '安红豆';
        console.log(monitor.time);
        console.log(monitor);
        console.log('has','name' in monitor,'time' in monitor);
    
        // delete monitor.time;
        // console.log('delete',monitor);
        // delete monitor._r;
        // console.log('delete',monitor);
        console.log('ownKeys',Object.keys(monitor));
    }
    
    输出结果: proxy输出结果

    Reflect

    {
        let obj={
            time:'2017-03-11',
            name:'net',
            _r:123
        };
    
        console.log('Reflect get',Reflect.get(obj,'time'));
        Reflect.set(obj,'name','mukewang');
        console.log(obj);
        console.log('has',Reflect.has(obj,'name'));
    }
    
    输出结果: reflect输出结果

    相关文章

      网友评论

          本文标题:ES6 6.Proxy和Reflect

          本文链接:https://www.haomeiwen.com/subject/ovrcmftx.html