JavaScript Proxy Target (ES6)

I want to be able to do this:

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

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

whereand gtare just examples. I do not know what functions will be called, they can be anything, and they do nothing but fill the array __calls.

So far I have the following code that uses ES6 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 delete the line return x, I can do x.where('age'); x.gt(20)to get the correct one __calls. However, return xfor some reason, it goes into infinite recursion ...

+3
source share
1 answer

console.log(name), , , , inspect constructor. :)

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

Source: https://habr.com/ru/post/1667939/


All Articles