相关疑难解决方法(0)

PHP等效的PHP __call

在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)

javascript

28
推荐指数
3
解决办法
9557
查看次数

在javascript中拦截函数调用

__callPHP中的魔法方法的等价物是什么?

我的印象是 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没有。我得到的不是函数错误。

javascript proxy function node.js

5
推荐指数
1
解决办法
3159
查看次数

是否可以使用代理来包装异步方法调用和错误处理?

是否可以使用代理来包装对具有错误处理的对象上的异步方法的调用?

我尝试了下面的代码,但是当代理方法中发生错误时,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)

我的目标是避免在每个代理方法中实现错误处理。

javascript error-handling proxy

2
推荐指数
1
解决办法
1253
查看次数

标签 统计

javascript ×3

proxy ×2

error-handling ×1

function ×1

node.js ×1