shopia T shopia T - 1 month ago 13
Javascript Question

use same function in every call of object

Ive object in js

var myobj = {}


I need that every time that you called to method in method like
myObj.a()

or
myObj.b()
etc it will call to the same function and will not call to anything else at all...

like myFn = function(){
return 1 + 1 ;
}

Answer

Ok so Proxy is one option.

It is ES6 and i do not believe it can be pollyfilled so no IE support I'm affraid. As you said thats not an issue then all good.

var obj = {};

var objProxied = new Proxy(obj, {
  get: (target, key, reciever) => {
    console.log(`Handler hit, looking for prop ${key}`);
    return (...args) => foo(...args); // return what ever you like here
  }
});

Essentially how it works is you provide the proxy with the object to be 'proxied' and a map of handlers. The MDN lists all the different handlers, if you do not provide a handler then it will call down unto the object.

Your handler is provided different things depending on the type of handler. In our case the get receives the object its being called upon, the original obj and the property name.

It is important to note your handler must return a value, (where the comment is in the example) if you do not it will call down to the underlying object. This would cause an exception in our example as we would try to execute an undefined method.

MDN

In action:

var obj = {};

function foo(...args) {
  console.log('foo called With:', ...args);
}

var objProxied = new Proxy(obj, {
  get: (target, key, reciever) => {
  	console.log(`Handler hit, looking for prop ${key}`);
    return (...args) => foo(...args)
  }
});

objProxied.a(10);
objProxied.b(20, 50);

Comments