• ES6(十一)Proxy和Reflect


    Proxy
    
    let obj = {
      time: '2019-01-01',
      name: 'ronle'
    }
    let monitor = new Proxy(obj, {
      // 拦截对象属性的读取
      get (target, key) {
        return target[key].replace('2019', '2020')
      },
      // 拦截对象设置属性
      set (target, key, value) {
        // 只有key等于name才修改
        if (key === 'name') {
          return Reflect.set(target, key, value)
        } else {
          return target[key]
        }
      },
      // 拦截 key in object操作
      has (target, key) {
        if (key === 'name') {
          return target[key]
        } else {
          return false
        }
      },
      // 拦截delete
      deleteProperty (target, key) {
        if (key.indexOf('-')) {
          delete target[key]
          return true
        } else {
          return target[key]
        }
      },
      // 拦截Object.keys
      // Object.getOwnPropertySymbols
      // Object.getOwnPropertyNames
      ownKeys (target) {
        return Object.keys(target).filter(item => item !== 'time')
      }
    })
    // 2020-01-01
    console.log('get', monitor.time)
    monitor.time = '2030'
    monitor.name = 'kaka'
    // 只有name被修改  kaka
    console.log('set', monitor, monitor.name)
    
    console.log('has', 'name' in monitor, 'time' in monitor)
    // // 删除掉日期
    // delete monitor.time
    // console.log('delete', monitor)
    
    // 返回不等于key不等于time的元素
    console.log('ownKeys', Object.keys(monitor))
    
    
    Reflect 跟proxy代理类似,方法属性都一样
    
    let obj = {
      time: '2019-01-01',
      name: 'ronle'
    }
    
    console.log(Reflect.get(obj, 'time'))
    Reflect.set(obj, 'name', 'kaka')
    console.log(obj)
    console.log(Reflect.has(obj, 'name'))
  • 相关阅读:
    Cannot resolve org.springframework:spring-web:5.2.2.BUILD-SNAPSHOT
    阿里规范最新泰山版下载
    Eureka启动连接报错Connect Refused
    SpringCloud集成feign和swagger导致feign报NullPointException
    js select 默认回显判断
    js 相差年、月、日
    mysql导出PDM文件步骤
    eclipse 安装反编译工具
    判断 List map set 是否为空
    mysql 5.7 版本的安装
  • 原文地址:https://www.cnblogs.com/ronle/p/11563989.html
Copyright © 2020-2023  润新知