首页  >  文章  >  web前端  >  如何在 JavaScript 中使用代理实现属性的无此类方法行为?

如何在 JavaScript 中使用代理实现属性的无此类方法行为?

Patricia Arquette
Patricia Arquette原创
2024-10-18 14:22:02641浏览

How to Implement No Such Method Behavior for Properties using Proxies in JavaScript?

为属性实现基于代理的 noSuchMethod

JavaScript 中的 noSuchMethod 功能允许拦截对不存在方法的调用。但是,是否有类似的属性机制?

ES6 代理来救援

ES6 代理提供了自定义属性访问的能力。我们可以利用它来模拟属性的类似 __noSuchMethod__ 的行为:

<code class="javascript">function enableNoSuchMethod(obj) {
  return new Proxy(obj, {
    get(target, p) {
      if (p in target) {
        return target[p];
      } else if (typeof target.__noSuchMethod__ == "function") {
        return function(...args) {
          return target.__noSuchMethod__.call(target, p, args);
        };
      }
    }
  });
}</code>

示例实现

这里是使用代理来实现可以处理未知属性的“Dummy”类的示例:

<code class="javascript">function Dummy() {
  this.ownProp1 = "value1";
  return enableNoSuchMethod(this);
}

Dummy.prototype.test = function() {
  console.log("Test called");
};

Dummy.prototype.__noSuchMethod__ = function(name, args) {
  console.log(`No such method ${name} called with ${args}`);
};

var instance = new Dummy();
console.log(instance.ownProp1);
instance.test();
instance.someName(1, 2);
instance.xyz(3, 4);
instance.doesNotExist("a", "b");</code>

用法

  • __ownProp1__:记录现有属性值。
  • __test__:触发定义的方法。
  • someName(1, 2)__:使用参数调用不存在的方法,该方法由 __noSuchMethod 钩子处理。
  • __xyz(3, 4)__:与上面类似,但演示了非- 还可以处理函数属性。
  • __doesNotExist("a", "b")__:使用提供的参数记录不存在方法/属性。

以上是如何在 JavaScript 中使用代理实现属性的无此类方法行为?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn