use same function in every call of object

前端 未结 1 1496
暗喜
暗喜 2021-01-07 12:57

Ive object in js

var myobj = {} 

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

相关标签:
1条回答
  • 2021-01-07 13:23

    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);

    0 讨论(0)
提交回复
热议问题