首頁 > web前端 > js教程 > 主體

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

Linda Hamilton
發布: 2024-10-18 14:19:03
原創
987 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!