1. 程式人生 > >Web端 es6(基礎九)Proxy 和 Reflect

Web端 es6(基礎九)Proxy 和 Reflect

Proxy

Proxy 物件用於定義基本操作的自定義行為(如屬性查詢,賦值,列舉,函式呼叫等)。

通俗的來講,也就是代理

let obj = {
    time: '2017-03-11',
    name: 'met',
    _r: 123
};
// 建立代理
let monitor = new Proxy(obj, {
    // 攔截物件屬性的讀取
    get(target, key) {
        // 講值進行替換
        return target[key].replace("2017", "2018")
    },
    // 攔截物件設定屬性
    set(target, key, value) {
        // 設定為 只允許修改 name
if (key === 'name') { return target[key] = value; } else { return target[key]; } }, // 攔截 key in object 操作 has(target, key) { if (key === 'name') { return target[key] } else { return false; } }, // 刪除屬性操作
deleteProperty(target,key){ // 存在下劃線 也就是 _r 允許刪除 if (key.indexOf('_') > -1){ delete target[key]; return true; }else{ return target[key]; } }, /** * 攔截 * Object.keys * Object.getOwnPropertySymbols() * Object.getOwnPropertyNames() * */
ownKeys(target){ return Object.keys(target).filter( item => item !== 'timer' ) } }); // 1. get 攔截測試 console.log('get', monitor.time); // 2. set 攔截測試 monitor.time = "2019"; monitor.name = '穆科文'; console.log('set', monitor); // 3. has 攔截測試 console.log('has', 'name' in monitor,'time' in monitor); // 4. 刪除操作 delete monitor.time; console.log('delete',monitor); delete monitor._r; console.log('delete',monitor); // 5. ownKeys console.log('own',Object.keys(monitor))

分別對應輸出結果

get 2018-03-11
set Proxy {time: "2017-03-11", name: "穆科文", _r: 123}
has true false
delete Proxy {time: "2017-03-11", name: "穆科文", _r: 123}
delete Proxy {time: "2017-03-11", name: "穆科文"}
own (2) ["time", "name"]

Reflect

其實 跟 Proxy 差不多一樣,基本一模一樣
我們來看下demo

let obj = {
    time: '2017-03-11',
    name: 'met',
    _r: 123
};
console.log('Reflect  get',Reflect.get(obj,'time'))
console.log('Reflect  get',Reflect.has(obj,'time'))
// 輸出結果
Reflect  get 2017-03-11
Reflect  get true