什么是 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
实际上处理函数调用到对象本身,即如果你做 new Proxy(someFunction, { apply: ... })
, apply
将在调用 someFunction
之前调用。
没有什么可以捕获对属性的调用,因为这会是多余的——get
已经在返回属性时处理了。您可以简单地返回一个函数,然后在调用时生成一些调试输出。
class MyClass{
constructor(){
return new Proxy(this, {
get: function(target, prop) {
return function() {
console.log('function call', prop, arguments);
return 42;
};
}
});
}
}
var inst = new MyClass();
console.log(inst.foo(123));
关于javascript - 拦截javascript中的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54171850/