Reflect常结合proxy使用,在这里所有的案例就直接结合proxy直接使用。如果不是很懂proxy可以支持戳连接查看相关资料

get

  1. let obj = {
  2. name: "前端伪大叔",
  3. age: 19
  4. }
  5. let newObj = new Proxy(obj, {
  6. get(target, property) {
  7. if (property in target)
  8. return Reflect.get(target, property)
  9. else
  10. throw new Error(`${property}不在${target}上面`)
  11. }
  12. })
  13. console.log(newObj.name); // 前端伪大叔
  14. console.log(newObj.hello); // Uncaught Error: hello不在[object Object]上面

set

  1. let obj = {
  2. name: "前端伪大叔",
  3. age: 19
  4. }
  5. let newObj = new Proxy(obj, {
  6. set(target,property,value){
  7. if(target[property] === value){
  8. return target[property]
  9. }else{
  10. return Reflect.set(target,property,value)
  11. }
  12. }
  13. })
  14. console.log(newObj.name);
  15. newObj.name = '前端伪大叔'
  16. console.log(newObj.name);
  17. newObj.name = '前端'
  18. console.log(newObj.name);

has

和in运算符同理

  1. let obj = {
  2. name: "前端伪大叔",
  3. age: 19
  4. }
  5. let newObj = new Proxy(obj, {
  6. has(target,property){
  7. return Reflect.has(target,property)
  8. }
  9. })
  10. console.log('name' in newObj); // true
  11. console.log('sex' in newObj) // false

deleteProperty

删除指定的元素和属性。返回 boolean

    let newObj = new Proxy(obj, {
        deleteProperty(target,property){
            return Reflect.deleteProperty(target,property)
        }
    })
    delete newObj.name
    console.log(newOb

isExtensible

判断对象是否可以扩容,如果传入的不是对象会直接报错

    let obj = {}
    let arr = []
    let fun = ()=>{}
    let str = 'a'
    let num = 123;
    let bool = false
    let any;
    console.log(Reflect.isExtensible(obj));
    console.log(Reflect.isExtensible(arr));
    console.log(Reflect.isExtensible(fun));
    // console.log(Reflect.isExtensible(str));    报错
    // console.log(Reflect.isExtensible(num));    报错
    // console.log(Reflect.isExtensible(bool));    报错
    // console.log(Reflect.isExtensible(any));    报错

preventExtensions

和上面的相反,preventExtensions 是把一个可以扩容的对象转为 不可扩容 ,返回boolean值。

    let obj = {}
    console.log(Reflect.isExtensible(obj));    //    true
    Reflect.preventExtensions(obj)    //    返回boolean值
    console.log(Reflect.isExtensible(obj));    //    false

ownKeys

获取所有对象的key值。以数组形式返回所有的key值。

    let obj = {
        name: "前端伪大叔",
        fun() {
            return 'hello world'
        },
        list: [1, 2, 3, 4]
    }
    console.log(Reflect.ownKeys(obj)['name']);    //     ["name", "fun", "list"]