首页 > web前端 > js教程 > ES6 代理可以模拟 JavaScript 中属性的 noSuchMethod 功能吗?

ES6 代理可以模拟 JavaScript 中属性的 noSuchMethod 功能吗?

Linda Hamilton
发布: 2024-10-18 14:19:03
原创
1145 人浏览过

Can ES6 Proxies Emulate the noSuchMethod Feature for Properties in JavaScript?

Emulating noSuchMethod for Properties in JavaScript with ES6 Proxies

The noSuchMethod feature allows for implementing custom behavior when accessing non-existent methods in certain JavaScript implementations. A similar functionality can be achieved for properties using ES6 proxies.

Using ES6 Proxies

Proxy objects offer custom behavior for fundamental operations like property lookup. By setting traps on property access, the behavior of noSuchMethod can be emulated:

<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>
登录后复制

Usage

For instance:

<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}`);
  return;
};

var instance = new Dummy();
console.log(instance.ownProp1); // value1
instance.test(); // Test called
instance.someName(1, 2); // No such method someName called with [1, 2]
instance.xyz(3, 4); // No such method xyz called with [3, 4]
instance.doesNotExist("a", "b"); // No such method doesNotExist called with ["a", "b"]</code>
登录后复制

This example illustrates that the proxy intercepts property access and, in case of non-existence, delegates to the noSuchMethod implementation, enabling custom behavior for properties that have not been explicitly defined.

以上是ES6 代理可以模拟 JavaScript 中属性的 noSuchMethod 功能吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板