Home > Web Front-end > JS Tutorial > body text

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

Linda Hamilton
Release: 2024-10-18 14:19:03
Original
987 people have browsed it

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>
Copy after login

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>
Copy after login

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.

The above is the detailed content of Can ES6 Proxies Emulate the noSuchMethod Feature for Properties in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!