JS Proxy对象使用的两个案例:校验器和属性私有化

校验器

const target = {
  _id: '1024',
  name: 'vuejs',
}

// 校验器
const validators = {
   name(val) {
     return Object.prototype.toString.call(val) === 'string';
   },
   _id(val) {
     return Object.prototype.toString.call(val) === 'number';
   }
}

const createValidator = (target, validators) => {
  return new Proxy(target, {
    _validator: validators,
    set(target, propKey, value, proxy) {
      let validator = this._validator[propKey](value)
      if(validator) {
        return Reflect.set(target, propKey, value, proxy)
      } else {
        throw Error(`无法设置属性为${propKey}的值为${value},类型不匹配`)
      }
    }
  })
}

const targetProxy = createValidator(target, validators)

// targetProxy.name = 1234 // Error: 无法设置属性为name的值为1234,类型不匹配
// targetProxy._id = '1234' // Error: 无法设置属性为_id的值为1234,类型不匹配

属性私有化

const target = {
  _id: '1024',
  name: 'vuejs',
}



const createProxy = (target) => {
  return new Proxy(target, {
    get: function(target, propKey, proxy) {
      if(propKey[0] === '_') {
        throw Error(`${propKey} is privated`)
      }
      return Reflect.get(target, propKey, proxy)
    },
    set: function(target, propKey, value, proxy) {
      if(propKey[0] === '_') {
        throw Error(`${propKey} is privated, can not set ${value}`)
      }
      return Reflect.set(target, propKey, value, proxy)
    }
  })
}

const targetProxy = createProxy(target)

// targetProxy._id = 123 // Error: _id is privated, can not set 123
// console.log(targetProxy._id) // Error: _id is privated
posted @ 2025-01-01 15:36  Felix_Openmind  阅读(14)  评论(0)    收藏  举报
*{cursor: url(https://files-cdn.cnblogs.com/files/morango/fish-cursor.ico),auto;}