ES2015 代理:断言代理与目标对象相同

ES2015 Proxy: Assert that proxy is the same as target object

有没有简单的方法断言一个对象是代理的目标对象?

const o = {};
const p = new Proxy(o, {});

相等运算符似乎不起作用,as outlined in this paper on page 6:

o == p; // false
o === p; // false
const q = new Proxy(o, {});
p === q; // false

除了对对象进行字符串化和重新解析之外,还有什么方法可以验证它们指的是同一个对象吗?

示例用例:

我想比较代理节点和非代理节点。由于我自己创建了代理,所以我知道会发生什么行为。

const nodeList = new Proxy(document.querySelectorAll('div'), {
  get(target, key) { return new Proxy(target[key], {}); }
});

const specificNode = document.querySelector('div[data-target]');

for (const node of nodeList) {
  if (node === specificNode) { doSomethingElse(); } // Never happens, even if specificNode is in the nodeList
}

自己创建代理的时候,也可以做成可比较的。例如给出一种识别其目标的方法:

const associatedTarget = Symbol();
const p = new Proxy(target[key], {});
p[associatedTarget] = target[key];
return p;

…
if (node[associatedTarget] === specificNode)

一个更好的想法可能是给每个目标一个单例代理,这样你就可以获得特定节点的代理并通过===进行比较:

const proxies = new WeakMap();
function makeUniqueProxy(t) {
  if (!proxies.has(t))
    proxies.set(t, new Proxy(t, {}));
  return proxies.get(t);
}

const nodeList = new Proxy(document.querySelectorAll('div'), {
  get(target, key) { return makeUniqueProxy(target[key]); }
});

const specificNode = makeUniqueProxy(document.querySelector('div[data-target]'));
//                   ^^^^^^^^^^^^^^^

for (const node of nodeList) {
  if (node === specificNode) { doSomethingElse(); } // just works
}

这种方法还有非常可取的 属性 即 nodeList[0] === nodeList[0]