首頁  >  文章  >  web前端  >  ES6 代理程式可以模擬 JavaScript 中屬性的 noSuchMethod 功能嗎?

ES6 代理程式可以模擬 JavaScript 中屬性的 noSuchMethod 功能嗎?

Linda Hamilton
Linda Hamilton原創
2024-10-18 14:19:03989瀏覽

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

使用ES6 代理程式模擬JavaScript 中的noSuchMethod 屬性

noSuch

使用 ES6 代理

代理物件為屬性查找等基本操作提供自訂行為。通過在屬性訪問上設置陷阱,可以模擬

noSuchMethod 的行為:

<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); // 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>
此範例說明代理攔截屬性訪問,如果屬性不存在,則委託給

noSuchMethod 實現,從而為尚未明確定義的屬性啟用自訂行為。

以上是ES6 代理程式可以模擬 JavaScript 中屬性的 noSuchMethod 功能嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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