Javascript 如何知道代理调用/访问是否嵌套?

Javascript 如何知道代理调用/访问是否嵌套?,javascript,object,proxy,Javascript,Object,Proxy,我和JS代理一起工作是为了好玩,并且取得了不错的进展。但目前这一切都在一个单一的层面上。如果进行嵌套调用/访问,我希望返回嵌套代理,否则只返回对象 // example calls/accesses data.settings = {fire: true}; data.settings.fire // nested call // returns true data.settings // top level call // returns {fire: true} // the prox

我和JS代理一起工作是为了好玩,并且取得了不错的进展。但目前这一切都在一个单一的层面上。如果进行嵌套调用/访问,我希望返回嵌套代理,否则只返回对象

// 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];
    }
  },
});

这可能吗?

只需使用“设置”陷阱即可。此“设置”陷阱示例在分配对象时代理对象。您可以根据需要修改标准,使其更加复杂

const whaticareaabout=['settings'、'mediaSettings'、'fire'、'video'];
常量代理={
获取:功能(对象、道具){
if(whaticareaount.includes(prop))console.log('Get…',prop);
返回对象[prop];
},
设置:功能(对象、属性、值){
如果(值的类型==='object'){
log('Proxy…',prop);
obj[prop]=新代理(值,代理);
}否则{
obj[prop]=值;
}
}
};
const p=新代理({},Proxy);
p、 设置={fire:true};
p、 settings.mediaSettings={video:false};
控制台日志(p.settings);
console.log(p.settings.mediaSettings)
这可能吗

不,不可能区分

const val = data.settings.fire; // two accesses


只在第二种情况下为
.settings
返回一个普通对象,而不是它的代理。

我在您的示例中根本看不到任何调用?我想说嵌套访问更准确,因为我没有调用函数所以@Bergi是对的,“settings”属性引用的对象在您的示例中没有代理,因此,“fire”属性的访问不会被拦截。这回答了你的问题吗?如果没有,也许您可以进一步解释您的问题,更好地解释您试图实现的目标。并且,正如@Bergi所述,在根对象上的“get”陷阱中,无法区分“settings”作为链的一部分被访问。如果nestedCall为true,则settings属性将在调用中被代理,但由于无法确定nestedCall是否可行,因此无法完成。
const obj = data.settings; // one access
const val = obj.fire; // another access