小程序支持部分Proxy,完全支持Reflect
Proxy
Proxy(代理/攔截) 是 ES6 中新增的一個(gè)特性。Proxy 讓我們能夠以簡潔易懂的方式控制外部對對象的訪問。
let obj = {
time: '2017-03-11',
name: 'net',
id:1,
_r: 123
};
let monitor = new Proxy(obj, {
// 類似讀取器
get(target, key) {
if (key.startsWith('_')) {
console.log('私有變量不能被訪問');
return null
}
return target[key].replace('2017', '2018')
},
// 類似設(shè)置器
set(target, key, value) {
if (key === 'name') {
return target[key] = value;
} else {
return target[key];
}
},
});
console.info(monitor, obj);
// monitor: {time: "2017-03-11", name: "net", id: 1, _r: 123}
// obj: {time: "2017-03-11", name: "net", id: 1, _r: 123}
console.info(monitor.time,obj.time);//2018-03-11 2017-03-11
console.info(monitor._r, obj._r);//私有變量不能被訪問 null 123
monitor.name='com'
console.info(obj.name, monitor.name); //com //com
console.info(monitor.id = 5); //5
console.info(obj.id); //1
let obj = {
time: '2017-03-11',
name: 'net',
id:1,
_r: 123
};
//Proxy攔截
let monitor = new Proxy(obj, {
// 攔截key in object操作
has(target, key) {
if (key === 'name') {
return 3
} else {
return false;
}
},
// 攔截delete
deleteProperty(target, key) {
if (key=='name') {
delete target[key];
return true;
} else {
return true;
}
},
});
console.log('name' in monitor, 'time' in monitor); //true false
delete monitor.time
console.log(monitor); // {time: "2017-03-11", name: "net", id: 1, _r: 123}
delete monitor.name
console.log(monitor); // {time: "2017-03-11", id: 1, _r: 123}
Reflect
Proxy有的方法Reflect都有,用法一致。Reflect常結(jié)合Proxy一起用
Reflect.get 方法允許你從一個(gè)對象中取值。就如同函數(shù)(function)里的 屬性訪問器 語法
// Object
var obj2 = { x: 1, y: 2 };
console.log(Reflect.get(obj2, 'x')) // 1
// Array
console.log(Reflect.get(['zero', 'one'], 1)) // "one"
let obj = {
time: '2017-03-11',
name: 'net',
_r: 123
};
Reflect.set(obj, 'name', 'mukewang');//{time: "2017-03-11", name: "mukewang", _r: 123}
Decorator 修飾器
小程序完全不支持,待VUE項(xiàng)目中再補(bǔ)用法