Chaining JavaScript (ES6) Proxy object

2019-05-17 07:09发布

I want to be able to do this:

x.where('age').gt(20);

x.__calls  // [['age', []], ['gt', [20]]]

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.

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;
            }
        }
    }
});

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...

1条回答
ゆ 、 Hurt°
2楼-- · 2019-05-17 07:29

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;
            }
        }
    }
});
查看更多
登录 后发表回答