1. 代理對象 proxy object
代理對象可以用來打包一個目標對象,並攔截該對象的基本操作(如:屬性查詢、賦值等)。基本操作裏的方法稱之爲陷阱(traps)。
(1). 語法
- let 變量名 = new Proxy(目標對象,目標對象的基本操作);
如:// 創建目標對象貓咪
let cat = {
name: 'lulu',
age: 3
};
// 查看貓咪有哪些屬性
let checkProperty = {
get(target, property){
if (property === 'name'){
return `Hi, my name is ${target.name}.`;
}
else {
return target[property];
} }
};
// 創建代理對象
let mimi = new Proxy(cat, checkProperty);
console.log(mimi.name); // Hi, my name is lulu.
(2). 常用代理對象的陷阱 proxy traps
- get、set、apply、construct、getPrototypeOf、setPrototypeOf、isExtensible、preventExtensions、getOwnPropertyDescriptor。
如:// 使用 set() 陷阱的例子。先創建目標對象貓咪
let cat = {
name: 'lulu',
age: 3
};
// 使用set()陷阱,設置貓咪的年齡
let setAge = {
set(target, property, value){
// 限定年齡變量的類型與數值範圍
if (property === 'age'){
if (typeof value !== 'number'){
throw new Error('Please use a number');
}
if(value < 0 || value > 20){
throw new Error(`Cat's age should more than 0 and less than 20.`);
}
}
return target[property] = value;
}
};
// 創建代理對象
let mimi = new Proxy(cat, setAge);
mimi.age = 6;
console.log(mimi.age); // 6
2. 反射 Reflection
ES6引進了一個新的全局對象Reflect,它可以在程序運行時操作對象的變量、屬性和方法。
(1). Reflect API的常用方法
所有Reflect對象的方法都是靜態的。
- 常用方法有:apply(), construct(), defineProperty(), deleteProperty(), get(), set(), has(), isExtensible()等。
擧個Reflect.construct()的例子,Reflect.construct()的語法為:Reflect.construct(目標對象,args[, 新對象]);
如:// 創建動物類
class Animals {
constructor(name, age){
this.name = name;
this.age = age;
}
get information() {
return `My name is ${this.name}, and I'm ${this.age} years old.`;
}
};
let cat = Reflect.construct(Animals, ['lulu', 3]);
console.log(cat.information); // My name is lulu, and I'm 3 years old.