首页 > 解决方案 > 如何创建将拦截 vanilla js 中的任何属性和函数调用的模拟对象?

问题描述

我想在 vanilla js 中创建对象,其行为如下:

var obj = MyObj()
obj.call.any.function() / should print something like "called MyObj with call.any.function()"
obj.some.other.method() / "called MyObj with some.other.method()"

我已经尝试过代理对象,但我只能做这样的事情:

class MyObj{
constructor(){
return new Proxy(this, {
  get: function(target, prop) {
    return function() {
      console.log('function call', prop, arguments);
      return;
    };
  }
});
}
}

仅适用于 obj.call() 之类的函数调用,但不适用于 obj.some.call()

标签: javascript

解决方案


推荐阅读