例如对象 a={},直接 a.b.c.d=1 赋值会报错,
通过代理对象,可以实现多层赋值,默认会给加上空对象,不报错;
var getProxy = (function(){
var handler = {
get: function(target, propKey, receiver) {
console.log(`getting ${propKey}!`);
let value = Reflect.get(target, propKey, receiver);
if(value === undefined) {
// 设置默认值,一个空对象 {}
value = target[propKey] = {};
}
return (typeof value)==='object'? new Proxy(value, handler) : value;
},
}
return obj=>new Proxy(obj, handler);
})();
// 例子
var a = {};
var p = getProxy(a);
p.b.c.d = 111; // 此时可以直接赋值;p["b"]["c"].d.e 也可以
console.log(a); // a = {b:{c:{d:1}}}