ES6 Proxy calling methods as properties

百般思念 提交于 2020-01-02 16:28:52

问题


I have the following class that is utilizing a Proxy for getting properties and methods:

class User extends Model {

    static table = 'users';
    _attributes = {
        id: 1,
        firstName: 'Testing',
        lastName: 'Test'
    };

    constructor() {
        return new Proxy(this, {
            get: function(target, name) {
                // proxy getting code for functions and properties
            }
        });
    }

    client() {
        return this.hasOne(Client, 'clientID');
    }
}

Within the get method of the proxy, retrieving attributes is trivial. I just check for their existence within _attributes, and return the value, otherwise null.

if (target._attributes.hasOwnProperty(propertyName)) {
    return target._attributes[name];
}

return null;

Then I can use it as:

const user = new User();
console.log(user.id); // returns 1
console.log(user.firstName); // returns "Testing"

Within the get method of proxy, I can also check if the property called was a function, and return the appropriate function as a result:

if (typeof target[name] === 'function') {
    const originalFunction = target[name];
    return function(...args) {
        return originalFunction.apply(this, args);
    };
}

Then I can use it as:

const user = new User();
user.client(); // Returns the return value of client() from the class

However, within the get function of the proxy, I am unable to differentiate between user.client() and user.client. In the first case, I want to return the result of the function. In the second case, I want to retrieve the result of the function, perform an additional step, and then return that.

In Pseudo-code:

if (property is a function call) {
    return property();
}
else if (property is a function, but not a function call) {
    return property().doSomethingElse();
}

Using a Proxy, can I tell the difference between user.client() and user.client from within the get method?

In PHP, this is possible using the magic methods __get vs __call, but I am looking for a way to do this in Javascript.

来源:https://stackoverflow.com/questions/46997086/es6-proxy-calling-methods-as-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!