使用ES6 Proxy和Reflect实现数据校验

// 数据校验
function validator(target, validator) {
	return new Proxy(target, {
	  _validator: validator,
	  set(target, key, value, proxy) {
		if (target.hasOwnProperty(key)) {
		  let va = this._validator[key]
		  if (!!va(value)) {
			return Reflect.set(target, key, value, proxy)
		  } else {
			throw Error(`不能设置${key}到${value}`)
		  }
		} else {
		  throw Error(`${key}不存在`)
		}
	  }
	})
}
const personValidators={
	name(val) {
	  return typeof val === 'string'
	},
	age(val) {
	  return typeof val === 'number' && val > 18
	}
}
class Person {
	constructor(name, age) {
	  this.name = name
	  this.age = age
	  return validator(this, personValidators)
	}
}

const person = new Person('Jack', 19)
console.log(person) // {name: "Jack", age: 19}
person.name = 'Ma'
console.log(person) //  {name: "Ma", age: 19}
// person.age = 17
// console.log(person) // Error

 

你可能感兴趣的:(JavaScript,前端基础,es6,Proxy,Reflect,es,js)