前言
写本《JavaScript简餐》系列文章的目的是记录在阅读学习《JavaScript高级程序设计(第4版)》一书时出现的各个知识点。虽是对读书的笔记和总结,但是希望它轻量、简洁、犀利,不会引起阅读疲劳,可以在碎片化时间和闲暇之余轻巧地沐浴一下知识点。每篇文章只针对一个小部分进行讲解式的梳理,来达到个人复习总结和分享知识的目的。
首先,我们要知道代理可以捕获13种不同的基本操作方法:
- get()
- set()
- has()
- defineProperty()
- getOwnPropertyDescriptor()
- deleteProperty()
- ownKeys()
- getPrototypeOf()
- setPrototypeOf()
- isExtensible()
- preventExtensions()
- apply()
- construct()
一、跟踪属性访问
使用代理可以在代码中实现一些有用的编程模式。通过捕获get、set、has等操作,可以知道对象属性什么时候被访问、被查询。把实现相应捕获器的某个对象代理放到应用中,可以监控这个对象在哪里被访问过。来看一下例子:const person = {
name: 'Lucy'
}
const proxy = new Proxy(person, {
get (target, property, receiver) {
console.log(`Getting ${property}`);
return Reflect.get(...arguments);
},
set (target, property, value, receiver) {
console.log(`Setting ${property}=${value}`);
return Reflect.set(...arguments);
}
});
proxy.name; // Getting name
proxy.age = 25; // Setting age=25
二、隐藏属性
代理内部实现对外部代码是不可见的,因此可以借此来隐藏目标对象上的属性。来看下面的代码:const hiddenProperties = ['name', 'age'];
const person = {
name: 'Lucy',
age: 25,
school: 'Tsinghua University'
}
const proxy = new Proxy (person, {
get (target, property, receiver) {
if (hiddenProperties.includes(property)) {
return undefined;
} else {
return Reflect.get(...arguments);
}
},
has (target, property, receiver) {
if (hiddenProperties.includes(property)) {
return false;
} else {
return Reflect.has(...arguments);
}
}
})
console.log(proxy.name); // undefined
console.log(proxy.age); // undefined
console.log(proxy.school); // Tsinghua University
console.log('name' in proxy); // false
console.log('age' in proxy); // false
console.log('school' in proxy); // true
三、属性验证
因为所有赋值操作都会触发set()捕获器,所以可以根据所赋的值决定是允许还是拒绝赋值:const person = {
name: 'Lucy'
}
const proxy = new Proxy (person, {
set (target, property, value, receiver) {
if (typeof value === 'number') {
return false;
} else {
return Reflect.set(...arguments);
}
}
});
proxy.name = 59;
console.log(proxy.name); // Lucy(因为59不是Number数据类型,所以视作赋值无效,所以name还是Lucy)
proxy.name = 'Jack';
console.log(proxy.name); // Jack(赋值生效)
四、函数与构造函数参数验证
跟保护和验证对象属性类似,也可对函数和构造函数参数进行审查。比如,可以让函数只接收某种类型的值:function doubleArray(...arr) {
const newArray = arr.map((item, index, array) => {
return item*2;
});
return newArray;
}
const proxy = new Proxy(doubleArray, {
apply(target, thisArg, argArray) {
for (const arg of argArray) {
if (typeof arg !== 'number') {
throw 'This function requires Number Array!!!'
}
}
return Reflect.apply(...arguments);
}
})
//这里要分别写一下打印信息,两个一起写的话只会打印后一个的结果。
console.log(proxy(1, 2, 3)); // [ 2, 4, 6 ]
console.log(proxy(5, 'six', 7)); // This function requires Number Array!!!
还有一个有用的地方是,我们可以用来要求实例化时必须给构造函数传参:
class Person {
constructor(name) {
this.name = name;
}
}
const proxy = new Proxy(Person, {
construct(target, argArray, newTarget) {
if (argArray[0] === undefined) {
throw 'Must give a argument when you are initializing a instance!!!'
} else {
console.log(Reflect.construct(...arguments));
return Reflect.construct(...arguments);
}
}
});
//这里要分别写一下打印信息,两个一起写的话只会打印后一个的结果。
new proxy('Lucy'); // Person { name: 'Lucy' }
new proxy(); // Must give a argument when you are initializing a instance!!!
五、数据绑定与可观察对象
通过代理可以把原本不相关的部分联系到一起。这样就可以实现各种模式,从而让不同的代码互操作。比如,可以将被代理的类绑定到一个全局实例集合,让所有创建的实例都被添加到这个集合中:const personList = [];
class Person {
constructor(name) {
this.name = name;
}
}
const proxy = new Proxy(Person, {
construct(target, argArray, newTarget) {
const newPerson = Reflect.construct(...arguments);
personList.push(newPerson);
return newPerson;
}
})
new proxy('Lucy');
new proxy('Jack');
new proxy('Bob');
console.log(personList);
// [
// Person { name: 'Lucy' },
// Person { name: 'Jack' },
// Person { name: 'Bob' }
// ]
另外,还可以把集合绑定到一个事件分派程序,每次插入新实例都会发送消息:
const personList = [];
function printPersonName(name) {
console.log(name);
}
const proxy = new Proxy(personList, {
set(target, property, value, receiver) {
const result = Reflect.set(...arguments);
if (result) {
printPersonName(Reflect.get(target, property, receiver));
}
return result;
}
});
proxy.push('Lucy'); // Lucy
proxy.push('Jack'); // Jack