可以使用Reflect和Proxy编写脱离值本身的校验,便于维护与重构。
代码如下:
//返回带校验规则的代理对象
function validator(target,validator){
return new Proxy(target,{
localValidator:validator,
set(target,key,value,proxy){
if(target.hasOwnProperty(key)){
let vafn = this.localValidator[key];
if(!vafn(value)){
throw new Error(`${value}值不符合规范`);
}else{
return Reflect.set(target,key,value,proxy);
}
}else{
throw new Error(`${key}属性不存在,不能设置其值`);
}
}
})
}
//校验规则
const userVlid={
name(val){
return typeof val === 'string';
},
password(val){
return typeof val === 'string' && val.length>6;
}
}
//用户类
class User{
constructor(name,password){
this.name = name;
this.password = password;
return validator(this,userVlid);
}
}
let user = new User('zhangsan','123456');
console.log(user);//{name: "zhangsan", password: "123456"}
user.password = '123';//Uncaught Error: 123值不符合规范
user.age = 18;//anli10.html:60 Uncaught Error: age属性不存在,不能设置其值
网友评论