js中的反射与代理的应用
- 观察者模式
function obsetver(target){
const proxy = new Proxy(target, {
get(target, propertyKey){
return Reflect.get(target, propertyKey)
},
set(target, propertyKey, value){
target[propertyKey] = value;
}
})
return proxy;
}
const target = {
a : 1,
b : 2
}
const obj = obsetver(target);
console.log( obj ); //Proxy {a: 1, b: 2}
obj.c = 33;
console.log( obj ); // Proxy {a: 1, b: 2, c: 33}
console.log( target ); // {a: 1, b: 2, c: 33}
- 偷懒的构造函数
class User{
// constructor(firstName, lastName, age){
// this.firstName = firstName;
// this.lastName = lastName;
// this.age = age;
// }
}
function constructorProxy(Class, ...propNames){
return new Proxy(Class, {
construct(target, argumentsList){
const obj = Reflect.construct(target, argumentsList);
propNames.forEach((name, i) => {
obj[name] = argumentsList[i];
})
return obj;
}
})
}
// const user = new User("宇","威", 23)
const UserProxy = constructorProxy(User,"firstName", "lastName","age")
const obj = new UserProxy("宇","威", 21);
console.log(obj)
- 可验证的函数参数
function sun(a,b){
return a + b;
}
function validatorFunction(func, ...types){
return new Proxy(func,{
apply(target, thisArgument, argumentsList){
// 判断看是否有类型不符
types.forEach( (t,i) => {
const arg = argumentsList[i];
if(typeof arg !== t){
throw new TypeError(`第${i + 1}个参数,不是${t}类型`);
}
} );
return Reflect.apply(target, thisArgument, argumentsList)
}
})
}
const func = validatorFunction(sun,"number","number");
const aa = func(1,4);
console.log( aa )