ES6中的Proxy对象代理

2021-12-09  本文已影响0人  月下小酌_dbd5

♣ 通过代理对象可以获取和操作原对象的属性

let obj = { name: 'tom', age: 18 }
    let proxyObj = new Proxy(obj, {})
    //通过proxy来操作obj
    proxyObj.name = 'abb'
    console.log(proxyObj.age); //18
    console.log(obj.name); // abb

♣ Proxy捕获器

♣ 捕获器很多具体看文档: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy
♣ 下面列举---Proxy捕获器
   let obj = { name: 'tom', age: 18 }
    let proxyObj = new Proxy(obj, {
      // 获取值的捕获器
      //target=obj  
      get: function (target, key) {
        console.log(`获取obj对象的${key}值---${obj[key]}`);
        return target[key]
      },
      // 设置值的捕获器
      set: function (target, key, newValue) {
        console.log(`设置obj对象的${key}值为---${newValue}`);
        return target[key] = newValue
      },
      has: function (target, key) {
         console.log(`监听到对象的${key}属性in操作`, target);
        key in target
      },
      deleteProperty: function (target, key) {
        delete target[key]
        console.log('del');
      }
    })
    //通过proxy来操作obj
    proxyObj.name = 'abb'
    proxyObj.name
    let hasShow = 'name' in proxyObj
    console.log(hasShow);
♣ 结果
image.png
♣ 特殊--用于函数对象(function foo())
 function foo () {}

    const fooProxy = new Proxy(foo, {
      apply: function (target, thisArg, argArray) {
        console.log("对foo函数进行了apply调用");
        return target.apply(thisArg, argArray)
      },
      construct: function (target, argArray, newTarget) {
        console.log("对foo函数进行了new调用");
        return new target(...argArray)
      }
    })

    fooProxy.apply({}, [1, 'ab', 2])
    new fooProxy('bd', 3, 4, 5)
♣ 结果
image.png
上一篇下一篇

猜你喜欢

热点阅读