"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Implement No Such Method Behavior for Properties using Proxies in JavaScript?

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

Published on 2024-11-09
Browse:155

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

Implementing Proxy-Based noSuchMethod for Properties

The noSuchMethod feature in JavaScript allows intercepting calls to non-existent methods. However, is there a similar mechanism for properties?

ES6 Proxies to the Rescue

ES6 Proxies provide the ability to customize property access. We can utilize this to emulate a __noSuchMethod__-like behavior for properties:

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

Example Implementation

Here's an example of using the proxy to implement a "Dummy" class that can handle unknown properties:

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");

Usage

  • __ownProp1__: Logs the existing property value.
  • __test__: Triggers the defined method.
  • someName(1, 2)__: Calls a non-existent method with arguments, which is handled by the __noSuchMethod hook.
  • __xyz(3, 4)__: Similar to above, but demonstrates that non-function properties can also be handled.
  • __doesNotExist("a", "b")__: Logs the absence of a method/property with the provided arguments.
Release Statement This article is reprinted at: 1729232480 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3