Javascript ES6代理调用方法作为属性
我有一个利用代理获取属性和方法的类:Javascript ES6代理调用方法作为属性,javascript,node.js,es6-proxy,Javascript,Node.js,Es6 Proxy,我有一个利用代理获取属性和方法的类: class User extends Model { static table = 'users'; _attributes = { id: 1, firstName: 'Testing', lastName: 'Test' }; constructor() { return new Proxy(this, { get: functio
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');
}
}
在代理的get方法中,检索属性非常简单。我只是在\u属性中检查它们是否存在,然后返回值,否则返回null
if (target._attributes.hasOwnProperty(propertyName)) {
return target._attributes[name];
}
return null;
然后我可以将其用作:
const user = new User();
console.log(user.id); // returns 1
console.log(user.firstName); // returns "Testing"
const user = new User();
user.client(); // Returns the return value of client() from the class
在proxy的get方法中,我还可以检查调用的属性是否是函数,并返回相应的函数作为结果:
if (typeof target[name] === 'function') {
const originalFunction = target[name];
return function(...args) {
return originalFunction.apply(this, args);
};
}
然后我可以将其用作:
const user = new User();
console.log(user.id); // returns 1
console.log(user.firstName); // returns "Testing"
const user = new User();
user.client(); // Returns the return value of client() from the class
但是,在代理的get函数中,我无法区分user.client()
和user.client
。在第一种情况下,我想返回函数的结果。在第二种情况下,我希望检索函数的结果,执行一个附加步骤,然后返回该步骤
在伪代码中:
if (property is a function call) {
return property();
}
else if (property is a function, but not a function call) {
return property().doSomethingElse();
}
使用代理,我可以从get方法中分辨出user.client()
和user.client
之间的区别吗
在PHP中,可以使用神奇的方法\uuuu get
vs\uu call
,但我正在寻找一种在Javascript中实现这一点的方法。您不应该对任何事情使用代理。它们是一种不合适的特征。getter和setter看起来在这里使用相同的接口也可以很好地工作。@Ryan您能详细说明一下吗?我不确定如何使用getter调用user.client
,并让它在应用附加操作的情况下返回函数的结果。类似于,ifuser.client()
只返回函数调用,否则ifuser.client
返回user.client().somethingElse()
你不能让user.client
根据是否被调用而采用不同的值。@Ryan这就是我的想法。真的很不幸,因为其他语言都支持这一点。我不认为这是不幸的——它会与程序员对表达式工作方式的期望相冲突。提供user.client
getter和user.foo('client')
方法更加明确。