{
function validator(target, validator, errorMsg) {
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(value) {
return value.length > 6;
},
age(value) {
return typeof value=== 'number' && value > 16;
}
}
class Person{
constructor(name,age){
this.name = name;
this.age = age;
return validator(this,personValidators);
}
}
const person = new Person('lilei',3);
console.log(person);
person.age = 2;
}
console