链接JavaScript(ES6)代理对象 [英] Chaining JavaScript (ES6) Proxy object
问题描述
我希望能够这样做:
x.where('age').gt(20);
x.__calls // [['age', []], ['gt', [20]]]
其中
和 gt
只是示例。我不知道会调用哪些函数,它们可能是任何函数,除了填充 __ calls
数组之外它们什么都不做。
where
and gt
are just examples. I do not know what functions will be called, they might be anything, and they don't do anything apart from filling the __calls
array.
到目前为止,我有以下代码使用ES6的代理对象
So far I have the following code which uses ES6's Proxy object
var x = new Proxy({
__calls: []
}, {
get: function (target, name) {
if (name in target) {
return target[name];
} else {
return () => {
target.__calls.push([name, Array.prototype.slice.call(arguments)]);
return x;
}
}
}
});
如果我删除返回x
行,我可以做 x.where('age'); x.gt(20)
获取正确的 __ calls
。但是,使用返回x
,由于某种原因它会进入无限递归...
If I remove the return x
line, I can do x.where('age'); x.gt(20)
to get the correct __calls
. However, with the return x
, it goes into infinite recursion for some reason...
推荐答案
我添加了 console.log(name)
来找出哪些调用负责无限递归,结果证明它是检查
和构造函数
。所以我只是将它们列入黑名单:)
I added console.log(name)
to find out what calls were responsible for the infinite recursion, and it turns out it was inspect
and constructor
. So I just blacklisted them :)
var x = new Proxy({
__calls: []
}, {
get: function (target, name) {
if (name in target || name === 'inspect' || name === 'constructor') {
return target[name];
} else {
return function() {
target.__calls.push([name, Array.prototype.slice.call(arguments)]);
return x;
}
}
}
});
这篇关于链接JavaScript(ES6)代理对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!