如何从代理对象获取代理的处理程序? [英] How to get proxy's handler from proxy object?

查看:151
本文介绍了如何从代理对象获取代理的处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有这个处理程序/代理(来自 MDN示例)...

For example, if I have this handler/proxy (from the MDN example)...

var handler = {
    get: function(target, name){
        return name in target?
            target[name] :
            37;
    }
};

var p = new Proxy({}, handler);
p.a = 1;
p.b = undefined;

console.log(p.a, p.b); // 1, undefined
console.log('c' in p, p.c); // false, 37

是否可以探测代理, p ,以某种方式允许我返回处理程序对象。

is it possible to probe the proxy, p, in some way that allows me to get the handler object back.

行:

p.__handler__   // returns handler object -> Object {get: handler.get(), set: handler.set(), ...}
p.__handler__.get  // returns get prop/fn of handler -> function(target, name){ ...}

显然,各种陷阱设置在处理程序中仍然知道代理,但有一个明确的方式从代理本身返回它们/处理程序?如果是这样,怎么做?

我目前没有具体的用例,但如果你想动态改变,我可以看到它很有用已有代理后的处理程序/陷阱。

I have no specific use-case for this at the moment, but I could see this being useful if you wanted to dynamically change a handler/traps after you already have a proxy.

推荐答案

ECMAScript无法访问内部[[ProxyHandler]]也无法访问[[ProxyTarget]]插槽。

ECMAScript provides no way to access the internal [[ProxyHandler]] nor [[ProxyTarget]] slots.

某些实现可能会提供一些非标准方式,但不要将其视为理所当然。

Some implementations may provide some non-standard ways, but don't take it for granted.

例如,在Firefox特权代码上,您可以使用

For example, on Firefox privileged code, you can know if an object is a proxy using

Components.utils.isProxy(object);

我建议实现类似的方法来公开[[ProxyHandler]]和[[ProxyTarget]]。他们告诉我在 Debugger.Object 而不是 Components.utils 中实现它们。

I proposed implementing similar methods to expose the [[ProxyHandler]] and [[ProxyTarget]]. They told me to implement them in Debugger.Object instead of Components.utils.

当补丁登陆时,可以使用类似

When the patch lands, it will be possible to use something like

Components.utils.import('resource://gre/modules/jsdebugger.jsm');
var Cc = Components.classes;

// Add a debugger to a new global
var global = new Components.utils.Sandbox(
  Cc["@mozilla.org/systemprincipal;1"].createInstance(Ci.nsIPrincipal),
  { freshZone: true }
);
addDebuggerToGlobal(global);
var dbg = new global.Debugger().addDebuggee(this);

// Create a debugger object of your object, and run proxy getters
var dbgObj = dbg.makeDebuggeeValue(object);
if(dbgObj.isProxy) { // a boolean
  dbgObj.proxyHandler.unsafeDereference(); // the [[ProxyHandler]]
  dbgObj.proxyTarget.unsafeDereference(); // the [[ProxyTarget]]
}

这篇关于如何从代理对象获取代理的处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆