首頁  >  文章  >  web前端  >  如何在 JavaScript 中模擬屬性級 noSuchMethod?

如何在 JavaScript 中模擬屬性級 noSuchMethod?

DDD
DDD原創
2024-10-18 14:29:03480瀏覽

How to Emulate Property-Level noSuchMethod in JavaScript?

在JavaScript 中模擬屬性級noSuchMethod

某些JavaScript 實作(例如Rhino 和SpiderMonkey)中的noSuch

ECMAScript 6 救援代理

ECMAScript 6 引入了代理,它提供了一種用於自訂基本操作(包括屬性存取)的機制。透過利用代理陷阱,我們可以使用 __noSuchMethod__ 模擬屬性來尋找所需的行為。

使用ES6 代理程式的解決方案

<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>
範例用法

考慮以下範例:

<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>
此程式碼將記錄以下輸出,並示範屬性的

noSuchMethod 模擬:

以上是如何在 JavaScript 中模擬屬性級 noSuchMethod?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn