Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Equivalent Of PHP __call

Tags:

javascript

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(); 
like image 954
Fenton Avatar asked Apr 19 '12 10:04

Fenton


1 Answers

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.

like image 98
Amir Nissim Avatar answered Oct 05 '22 14:10

Amir Nissim