在PHP中,您可以使用"魔术" __call
功能检测方法何时被调用,即使它不存在.
public function __call($methodName, $args)
{
// do something
}
Run Code Online (Sandbox Code Playgroud)
您可以调用任何方法,并将名称和参数传递给此魔法catch-all.
在JavaScript中是否有类似的技术允许调用任何方法,即使它实际上不存在于对象上?
var foo = (function () {
return {
__call: function (name, args) { // NOT REAL CODE
alert(name); // "nonExistent"
}
}
}());
foo.nonExistent();
Run Code Online (Sandbox Code Playgroud) __call
PHP中的魔法方法的等价物是什么?
我的印象是 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));
Run Code Online (Sandbox Code Playgroud)
get
似乎有效,因为我看到“get foo”,但apply
没有。我得到的不是函数错误。
是否可以使用代理来包装对具有错误处理的对象上的异步方法的调用?
我尝试了下面的代码,但是当代理方法中发生错误时,catch 不会执行。
const implementation = {
// proxied async methods here
}
const proxy = new Proxy(implementation, {
get: (target, prop, reciever) => {
try {
return Reflect.get(target, prop, reciever)
}
catch (error) {
console.log('Error:')
console.error(error)
}
}
})
Run Code Online (Sandbox Code Playgroud)
我的目标是避免在每个代理方法中实现错误处理。