一、Proxy 是什么?
Proxy 对象用于拦截并修改目标对象的指定操作。
const p = new Proxy(target, handler)
- target :目标对象(可以是任何类型的对象,包括原生数组,函数,甚至另一个代理)。
- handler :以函数作为属性的对象,实现拦截和自定义操作。
二、怎么用?
1、使用 Proxy 的简单实例
访问不存在的属性,设置默认值返回而不返回 undefined ,get handler 有其具体语法规则,看这里!
const handler = {
get: function(obj, prop) {
return prop in obj ? obj[prop] : 37;
}
};
const p = new Proxy({}, handler);
p.a = 1;
p.b = undefined;
console.log(p.a, p.b);
console.log('c' in p, p.c);
2、目标对象被正确修改
let target = {};
let p = new Proxy(target, {});
p.a = 37;
console.log(target.a);
3、使用 set handler 做数据验证
set handler 有其具体的语法规则,看这里!
let validator = {
set: function(obj, prop, value) {
if (prop === 'age') {
if (!Number.isInteger(value)) {
throw new TypeError('The age is not an integer');
}
if (value > 200) {
throw new RangeError('The age seems invalid');
}
}
obj[prop] = value;
return true;
}
};
let person = new Proxy({}, validator);
person.age = 100;
console.log(person.age);
person.age = 'young';
person.age = 300;
4、扩展构造函数
construct handler 的具体语法规则,看这里!
function extend(sup, base) {
var descriptor = Object.getOwnPropertyDescriptor(
base.prototype, "constructor"
);
base.prototype = Object.create(sup.prototype);
var handler = {
construct: function(target, args) {
var obj = Object.create(base.prototype);
this.apply(target, obj, args);
return obj;
},
apply: function(target, that, args) {
sup.apply(that, args);
base.apply(that, args);
}
};
var proxy = new Proxy(base, handler);
descriptor.value = proxy;
Object.defineProperty(base.prototype, "constructor", descriptor);
return proxy;
}
var Person = function (name) {
this.name = name
};
var Boy = extend(Person, function (name, age) {
this.age = age;
});
Boy.prototype.sex = "M";
var Peter = new Boy("Peter", 13);
console.log(Peter.sex);
console.log(Peter.name);
console.log(Peter.age);
三、参考文档
|