ES6 Proxy代理

2022/6/28 Proxy代理ES6

Proxy代理中的函数作用

# proxy

  • proxy 有get set
  1. get 是获取值的钩子函数
  2. set 是设置值的钩子函数
  3. has是判断当前对象有没有这个 键(有没有这个属性名)
  4. ownKeys是遍历循环拦截
  5. apply是调用函数的时候拦截
  6. deleteProperty是删除的时候拦截
 let arr = ['a', 'b', 'c']
        arrs = new Proxy(arr, {
            get(arr, index) {             // 判断数组中是否有这个数值
                return index in arr ? '有' : '否'
            },
            set(item, index, val) {      // 数组添加类型必须是字符串
                if (typeof val == 'string') {
                    item.push(val)
                } else {
                    console.log('错误');
                }
            }
        })
        console.log(arrs[3]); // 输出 否
        arrs[3] = 4
        console.log(arr);  // 输出 错误
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  const obj = {
            name: 'name',
            age: '12'
        }
        objs = new Proxy(obj, {
            has(target, item) {
                return target[item];
            }
        })
        console.log('age' in objs); // 返回true
1
2
3
4
5
6
7
8
9
10
      const obj = {
            name: 'name',
            age: '12',
        }
        objs = new Proxy(obj, {
            ownKeys(target) {
                return Object.keys(target).filter(item => !item.startsWith('a'))
            }
        })

        for (let i in objs) {
            console.log(i);   // age 被隐藏
        }
1
2
3
4
5
6
7
8
9
10
11
12
13
 function add(...a) {
            let c = 0
            a.forEach(item => {
                c += item
            })
            return c
        }
        const q = new Proxy(add, {
            apply(a, b, c) {
                return a(...c) * 5
            }
        })
        console.log(q(1, 2, 3, 4));
1
2
3
4
5
6
7
8
9
10
11
12
13
   const obj = {
            id: 0,
            age: "徐涛"
        }
        const objs = new Proxy(obj, {
            deleteProperty(a, b) {
                if (b.startsWith('i')) {
                    console.log('不能删除');
                } else {
                    delete a[b]
                }
            }
        })
        delete objs.age
        console.log(objs);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15