【发布时间】:2019-01-13 18:21:24
【问题描述】:
PHP 中的 __call 魔术方法等效于什么?
我的印象是 Proxy 可以做到这一点,但它不能。
class MyClass{
constructor(){
return new Proxy(this, {
apply: function(target, thisArg, args){
console.log('call', thisArg, args);
return 'test';
},
get: function(target, prop){
console.log('get', prop, arguments);
}
});
}
}
var inst = new MyClass();
console.log(inst.foo(123));
get 似乎工作,因为我看到“get foo”,但 apply 没有。我得到的不是函数错误。
【问题讨论】:
-
代理上的
apply陷阱如果用于调用对象本身,即inst(…)。但是,您不能从不可调用的目标创建可调用代理。 -
get属性上的.foo陷阱必须返回一个函数,以便您可以调用它。
标签: javascript node.js function proxy