ES6 (下)

小程序支持部分Proxy,完全支持Reflect

Proxy

Proxy(代理/攔截) 是 ES6 中新增的一個(gè)特性。Proxy 讓我們能夠以簡潔易懂的方式控制外部對對象的訪問。

 let obj = {
        time: '2017-03-11',
        name: 'net',
        id:1,
        _r: 123
      };
      
      let monitor = new Proxy(obj, {
        // 類似讀取器
        get(target, key) {
            if (key.startsWith('_')) {
               console.log('私有變量不能被訪問');
                return null
            }
            return target[key].replace('2017', '2018')
        }, 
        // 類似設(shè)置器
        set(target, key, value) {
          if (key === 'name') {
            return target[key] = value;
          } else {
            return target[key];
          }
        },
      });

       console.info(monitor, obj); 
      // monitor:   {time: "2017-03-11", name: "net", id: 1, _r: 123}
      // obj:    {time: "2017-03-11", name: "net", id: 1, _r: 123}

      console.info(monitor.time,obj.time);//2018-03-11   2017-03-11   
      console.info(monitor._r, obj._r);//私有變量不能被訪問 null   123   

      monitor.name='com' 
      console.info(obj.name, monitor.name);  //com  //com
      console.info(monitor.id = 5); //5
      console.info(obj.id); //1
  let obj = {
        time: '2017-03-11',
        name: 'net',
        id:1,
        _r: 123
      };
      //Proxy攔截 
      let monitor = new Proxy(obj, {
        // 攔截key in object操作
        has(target, key) {
          if (key === 'name') {
            return 3
          } else {
            return false;
          }
        },
        // 攔截delete
        deleteProperty(target, key) {
          if (key=='name') {
            delete target[key];
            return true;
          } else {
            return true;
          }
        },
      });

      console.log('name' in monitor, 'time' in monitor);  //true  false 
      delete monitor.time
      console.log(monitor); // {time: "2017-03-11", name: "net", id: 1, _r: 123}
      
      delete monitor.name
      console.log(monitor); // {time: "2017-03-11", id: 1, _r: 123}

Reflect

Proxy有的方法Reflect都有,用法一致。Reflect常結(jié)合Proxy一起用
Reflect.get 方法允許你從一個(gè)對象中取值。就如同函數(shù)(function)里的 屬性訪問器 語法

      // Object
      var obj2 = { x: 1, y: 2 };
      console.log(Reflect.get(obj2, 'x')) // 1

      // Array
      console.log(Reflect.get(['zero', 'one'], 1)) // "one"

      let obj = {
        time: '2017-03-11',
        name: 'net',
        _r: 123
      }; 
      Reflect.set(obj, 'name', 'mukewang');//{time: "2017-03-11", name: "mukewang", _r: 123}

Decorator 修飾器

小程序完全不支持,待VUE項(xiàng)目中再補(bǔ)用法

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容