我想允许在 JavaScript 对象上使用动态方法 calls,即即使该对象没有定义该方法,它仍然应该是可调用的(例如使用默认的虚拟对象)。
const obj = {a: 5};
obj.dynamicMethodCallWithAnyNameYouWant(); // should work
obj.a; // should work, value is 5
obj.b; // should yield undefined
现在有了 JS 代理,我们可以做这样的事情来获得正确的方向:
const obj = new Proxy({a: 5}, {
get(target, prop, receiver) {
// If the property does not exist, define it as a new function
if (!(prop in target)) {
target[prop] = function() {
console.log(`Method ${prop} has been dynamically created and invoked!`);
};
}
return Reflect.get(target, prop, receiver);
}
});
obj.dynamicMethodCallWithAnyNameYouWant();
console.log(obj.a); // prints 5
const res = obj.thisShouldYieldUndefinedInsteadOfCreatingAFunction
res(); // this prints "Method thisShouldYieldUndefined ..."
问题是我们无法检测该属性是否被访问或调用因为
[...] JavaScript 不区分属性和方法。这只是访问的属性,如果它是函数,则可以调用它们的值。 ~ 这个答案
是否有其他方法可以实现所需的行为,例如有替代代理方法吗?
不,这是不可能的。如果
obj.b
产生 undefined
,那么 obj.b()
将抛出异常。如果 obj.dynamicMethodCallWithAnyNameYouWant()
是有效的方法调用,则 obj.dynamicMethodCallWithAnyNameYouWant
将必须返回一个函数,而不是 undefined
。