[英]Chaining JavaScript (ES6) Proxy object
I want to be able to do this:我希望能够做到这一点:
x.where('age').gt(20);
x.__calls // [['where', ['age']], ['gt', [20]]]
where
and gt
are just examples. where
和gt
只是示例。 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.我不知道会调用什么函数,它们可能是任何东西,除了填充
__calls
数组之外,它们什么也不做。
So far I have the following code which uses ES6's Proxy object到目前为止,我有以下代码使用 ES6 的Proxy对象
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;
}
}
}
});
If I remove the return x
line, I can do x.where('age'); x.gt(20)
如果我删除
return x
行,我可以执行x.where('age'); x.gt(20)
x.where('age'); x.gt(20)
to get the correct __calls
. x.where('age'); x.gt(20)
以获得正确的__calls
。 However, with the return x
, it goes into infinite recursion for some reason...然而,随着
return x
,它出于某种原因进入无限递归......
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
.我添加了
console.log(name)
来找出导致无限递归的调用,结果是inspect
和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;
}
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.