ES6 reflect对象与proxy

Reflect对象的方法与Proxy对象的方法一一对应,只要是Proxy对象的方法,就能在Reflect对象上找到对应的方法。Reflect对象一共有 13 个静态方法,可以理解为统一的对象操作API:

Reflect.apply(target, thisArg, args)
Reflect.construct(target, args)
Reflect.get(target, name, receiver)
Reflect.set(target, name, value, receiver)
Reflect.defineProperty(target, name, desc)
Reflect.deleteProperty(target, name)
Reflect.has(target, name)
Reflect.ownKeys(target)
Reflect.isExtensible(target)
Reflect.preventExtensions(target)
Reflect.getOwnPropertyDescriptor(target, name)
Reflect.getPrototypeOf(target)
Reflect.setPrototypeOf(target, prototype)

上面这些方法的作用,大部分与Object对象的同名方法的作用都是相同的。

proxy构造函数中的方法:

const obj = {
  name: 'zs',
  age: 18
};
const objProxy = new Proxy(obj, {
  get(target, property) {
    console.log(target, property);   // { name: 'zs', age: 18 } name     { name: 'zs', age: 18 } a
    return property in target ? target[property] : 'defaultValue';
  },
  set(target, property, value) {
    console.log(target, property, value);  // { name: 'zs', age: 18 } sex man       { name: 'zs', age: 18, sex: 'man' } age 12
    if (property === 'age') {
      if (!Number.isInteger(value)) {
        throw new TypeError(`${value} is not an int`);
      }
    }
    target[property] = value;
  }
});
console.log(objProxy.name);  // zs
console.log(objProxy.a);  //  defaultValue
objProxy.sex = 'man';
console.log(objProxy);  // { name: 'zs', age: 18, sex: 'man' }
objProxy.age = '12';  
/** throw new TypeError(`${value} is not an int`);
        ^
TypeError: 12 is not an int */ 

reflect静态方法:

const obj = {
  name: 'zs',
  age: 18
};
const objProxy = new Proxy(obj, {
  get(target, property) {
    return Reflect.get(target, property);
  }
});
console.log(objProxy.name);  // zs


const obj = {
  name: 'zs',
  age: 18
};
// console.log('age' in obj);
// console.log(delete obj['name']);
// console.log(Object.keys(obj));
console.log(Reflect.has(obj, 'age'));  // true
console.log(Reflect.deleteProperty(obj, 'age'));  // true
console.log(Reflect.ownKeys(obj));  // [ 'name' ]

上一篇:第三十六篇:vue3响应式(关于Proxy代理对象,Reflect反射对象)


下一篇:golang基础之反射