Emulating noSuchMethod for Properties in JavaScript with ES6 Proxies
The noSuchMethod feature allows for implementing custom behavior when accessing non-existent methods in certain JavaScript implementations. A similar functionality can be achieved for properties using ES6 proxies.
Using ES6 Proxies
Proxy objects offer custom behavior for fundamental operations like property lookup. By setting traps on property access, the behavior of noSuchMethod can be emulated:
<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>
Usage
For instance:
<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>
This example illustrates that the proxy intercepts property access and, in case of non-existence, delegates to the noSuchMethod implementation, enabling custom behavior for properties that have not been explicitly defined.
以上是ES6 代理可以模拟 JavaScript 中属性的 noSuchMethod 功能吗?的详细内容。更多信息请关注PHP中文网其他相关文章!