问题描述
我想测试一个 JavaScript 对象是否是 代理.琐碎的方法
I would like to test if a JavaScript object is a Proxy. The trivial approach
if (obj instanceof Proxy) ...
在这里不起作用,也不会遍历 Proxy.prototype
的原型链,因为所有相关操作都由底层目标有效支持.
doesn't work here, nor does traversing the prototype chain for Proxy.prototype
, since all relevant operations are effectively backed by the underlying target.
是否可以测试任意对象是否为代理?
Is it possible to test if an arbitrary object is a Proxy?
推荐答案
在我当前的项目中,我还需要一种方法来定义某物是否已经是代理,主要是因为我不想在代理上启动代理.为此,我只是在我的处理程序中添加了一个 getter,如果请求的变量是__Proxy",它将返回 true:
In my current project I also needed a way of defining if something was already a Proxy, mainly because I didn't want to start a proxy on a proxy. For this I simply added a getter to my handler, which would return true if the requested variable was "__Proxy":
function _observe(obj) {
if (obj.__isProxy === undefined) {
var ret = new Proxy(obj || {}, {
set: (target, key, value) => {
/// act on the change
return true;
},
get: (target, key) => {
if (key !== "__isProxy") {
return target[key];
}
return true;
}
});
return ret;
}
return obj;
}
可能不是最好的解决方案,但我认为这是一个优雅的解决方案,在序列化时也不会弹出.
Might not be the best solution, but I think it's an elegant solution, which also doesn't pop up when serializing.
这篇关于如何测试对象是否是代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!