In PHP you can detect when a method is called even when it doesn't exist using the "magic" __call
function.
public function __call($methodName, $args) { // do something }
You can call any method and the name and arguments are passed to this magic catch-all.
Is there a similar technique in JavaScript that would allow any method to be called even if it actually didn't exist on the object?
var foo = (function () { return { __call: function (name, args) { // NOT REAL CODE alert(name); // "nonExistent" } } }()); foo.nonExistent();
It is possible using the ES6 Proxy API:
var myObj = {}; var myProxy = new Proxy(myObj, { get: function get(target, name) { return function wrapper() { var args = Array.prototype.slice.call(arguments); console.log(args[0]); return "returns: " + args[0]; } } }); console.log(myProxy.foo('bar'));
Browser compatibility is available on MDN. As of August 2017 all browsers (including Microsoft Edge) except Internet Explorer support it.
See this answer for a more complete look at Proxy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With