」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 JavaScript 中模擬屬性的 noSuchMethod 功能?

如何在 JavaScript 中模擬屬性的 noSuchMethod 功能?

發佈於2024-11-08
瀏覽:394

How to Simulate the noSuchMethod Feature for Properties in JavaScript?

如何在JavaScript 中實現noSuchMethod 屬性功能

在JavaScript 中,noSuchMethod

在JavaScript 中,

noSuchMethod

雖然標準 JavaScript 語言中的屬性沒有直接等效項,但可以模擬類似的屬性使用 ECMAScript 6 代理程式的功能。 ECMAScript 6 的發布引入了 Proxies,這是一個強大的工具,可讓您攔截屬性存取並定義自訂行為。

    要為屬性實作類似__noSuchMethod__ 的功能,您可以使用下列方法:
定義一個覆蓋「get」陷阱的自訂代理程式處理程序:
get: function(target, property) {
  if (property in target) {
    // Return the property value if it exists
    return target[property];
  } else if (typeof target.__noSuchMethod__ == "function") {
    // Call the __noSuchMethod__ method with the property name
    // as the first argument and any additional arguments as the rest
    return function(...args) {
      return target.__noSuchMethod__.call(target, property, args);
    };
  }
}
    get: function(target, property) { if(目標中的屬性){ // 如果存在則傳回屬性值 返回目標[屬性]; } else if (typeof target.__noSuchMethod__ == "函數") { // 使用屬性名稱呼叫 __noSuchMethod__ 方法 // 作為第一個參數,任何其他參數作為其餘參數 返回函數(...args){ return target.__noSuchMethod__.call(目標、屬性、參數); }; } }
建立一個函數來啟用此行為:
get: function(target, property) {
  if (property in target) {
    // Return the property value if it exists
    return target[property];
  } else if (typeof target.__noSuchMethod__ == "function") {
    // Call the __noSuchMethod__ method with the property name
    // as the first argument and any additional arguments as the rest
    return function(...args) {
      return target.__noSuchMethod__.call(target, property, args);
    };
  }
}
    function enableNoSuchMethod(obj) { 返回新的 Proxy(obj, getTrapHandler); }
使用enableNoSuchMethod函數來包裝你的代理對象:
get: function(target, property) {
  if (property in target) {
    // Return the property value if it exists
    return target[property];
  } else if (typeof target.__noSuchMethod__ == "function") {
    // Call the __noSuchMethod__ method with the property name
    // as the first argument and any additional arguments as the rest
    return function(...args) {
      return target.__noSuchMethod__.call(target, property, args);
    };
  }
}

const proxy = enableNoSuchMethod({ __noSuchMethod__:函數​​(名稱,參數){ console.log(`沒有使用 ${args} 存取此類屬性 ${name}`); } }); console.log(proxy.someProperty); // 記錄「No such property someProperty accessed with []」透過應用此方法,您可以使用ECMAScript 6 代理程式模擬JavaScript 中屬性的

noSuchMethod

noSuchMethodHow to Simulate the noSuchMethod Feature for Properties in JavaScript? ] 的行為。此技術可讓您動態處理屬性訪問,並提供一種在嘗試存取不存在的屬性時實現自訂行為的方法。

版本聲明 本文轉載於:1729232959如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3