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