小程序支持部分Proxy,完全支持Reflect
Proxy
Proxy(代理/拦截) 是 ES6 中新增的一个特性。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')
},
// 类似设置器
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常结合Proxy一起用
Reflect.get 方法允许你从一个对象中取值。就如同函数(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项目中再补用法