Maison > interface Web > js tutoriel > le corps du texte

Comment émuler noSuchMethod au niveau de la propriété en JavaScript ?

DDD
Libérer: 2024-10-18 14:29:03
original
480 Les gens l'ont consulté

How to Emulate Property-Level noSuchMethod in JavaScript?

Emulating Property-Level noSuchMethod in JavaScript

The noSuchMethod feature in certain JavaScript implementations, such as Rhino and SpiderMonkey, allows for handling of unimplemented methods. However, a similar feature is not natively available for properties.

ECMAScript 6 Proxies to the Rescue

ECMAScript 6 introduced Proxies, which provide a mechanism for customizing fundamental operations, including property access. By leveraging Proxy traps, we can emulate the desired behavior for property lookups using __noSuchMethod__.

Solution Using ES6 Proxies

<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>
Copier après la connexion

Example Usage

Consider the following example:

<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);
instance.test();
instance.someName(1, 2);
instance.xyz(3, 4);
instance.doesNotExist("a", "b");</code>
Copier après la connexion

This code will log the following output, demonstrating the noSuchMethod emulation for properties:

value1
Test called
No such method someName called with 1,2
No such method xyz called with 3,4
No such method doesNotExist called with a,b
Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!