The noSuchMethod feature in JavaScript allows intercepting calls to non-existent methods. However, is there a similar mechanism for properties?
ES6 Proxies provide the ability to customize property access. We can utilize this to emulate a __noSuchMethod__-like behavior for properties:
<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>
Here's an example of using the proxy to implement a "Dummy" class that can handle unknown properties:
<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}`); }; var instance = new Dummy(); console.log(instance.ownProp1); instance.test(); instance.someName(1, 2); instance.xyz(3, 4); instance.doesNotExist("a", "b");</code>
The above is the detailed content of How to Implement No Such Method Behavior for Properties using Proxies in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!