我和JS Proxies一起工作很有趣并取得了不错的进展。但目前它只是一个层面。我想要的是,如果我正在进行嵌套调用/访问,则返回嵌套代理,否则只返回该对象。
// example calls/accesses
data.settings = {fire: true};
data.settings.fire // nested call
// returns true
data.settings // top level call
// returns {fire: true}
// the proxy code
const data = new Proxy({}, {
get: function(target, property, receiver) {
// how to figure out nestedCall?
if (nestedCall) {
return new Proxy(target[property], {
get: function(subTarget, subProperty, subReceiver) {
return 'nonsense, there is nothing nested here';
}.
});
}
else {
return target[property];
}
},
});
这甚至可能吗?
答案 0 :(得分:2)
这甚至可能吗?
不,无法区分
<div class="flex-container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
</div>
这
const val = data.settings.fire; // two accesses
并仅在第二种情况下为const obj = data.settings; // one access
const val = obj.fire; // another access
返回普通对象而不是代理对象。
答案 1 :(得分:1)
只需使用'设置'陷阱。这个'set'陷阱示例代表对象的分配。您可以根据需要将标准更改为更复杂。
const whatICareAbout = ['settings', 'mediaSettings', 'fire', 'video'];
const proxy = {
get: function(obj, prop) {
if(whatICareAbout.includes(prop)) console.log('Get...', prop);
return obj[prop];
},
set: function(obj, prop, value) {
if(typeof value === 'object') {
console.log('Proxy...', prop);
obj[prop] = new Proxy(value, proxy);
} else {
obj[prop] = value;
}
}
};
const p = new Proxy({}, proxy);
p.settings = {fire: true};
p.settings.mediaSettings = {video: false};
console.log(p.settings);
console.log(p.settings.mediaSettings);