>  기사  >  웹 프론트엔드  >  JavaScript에서 속성 수준 noSuchMethod를 에뮬레이트하는 방법은 무엇입니까?

JavaScript에서 속성 수준 noSuchMethod를 에뮬레이트하는 방법은 무엇입니까?

DDD
DDD원래의
2024-10-18 14:29:03480검색

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>

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>

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

위 내용은 JavaScript에서 속성 수준 noSuchMethod를 에뮬레이트하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.