如何在JavaScript 中實現noSuchMethod 屬性功能
在JavaScript 中,noSuchMethod
在JavaScript 中,noSuchMethod
雖然標準 JavaScript 語言中的屬性沒有直接等效項,但可以模擬類似的屬性使用 ECMAScript 6 代理程式的功能。 ECMAScript 6 的發布引入了 Proxies,這是一個強大的工具,可讓您攔截屬性存取並定義自訂行為。
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 (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 (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 中屬性的
noSuchMethodnoSuchMethod ] 的行為。此技術可讓您動態處理屬性訪問,並提供一種在嘗試存取不存在的屬性時實現自訂行為的方法。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3