Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a function every time any function in class is called using JS

Tags:

javascript

I have simple class like this:

module.exports = class MyClass {

    function middleware() {
        console.log('call me before')
    }

    function a() {

    }
    function b() {

    }

    function c() {

    }
}

So Idea is, when someone call function a, b, c I want call middleware before execute a, b, c. How can I do it?

So, I can put middleware() to each function, but I want some dynamic way how to do this.

like image 720
kinacexoli Avatar asked Aug 17 '18 21:08

kinacexoli


People also ask

How do you always call a function in JavaScript?

Answer: Use the JavaScript setInterval() method You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period. The setInterval() method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.

Which JavaScript function is used to call a function repeatedly after a certain time?

The setInterval() method repeats a given function at every given time-interval.

How do you call a function inside a class in JavaScript?

var test = new MyObject(); and then do this: test. myMethod();

Which JavaScript function is used to execute a task only once?

Both setTimeout() and setInterval() are built-in methods of the global object on the Document Object Model to schedule tasks at a set time. setTimeout() calls a passed-in function once after a specified delay, while setInterval() invokes one continuously at a designated time.


1 Answers

You could use Proxy in order to trap every property access on the instance, and wrap functions.

class MyClass {
  constructor() {
    const handler = {
      get: function (obj, prop) {
        return typeof obj[prop] !== "function"
          ? obj[prop]
          : function (...args) {
              obj.middleware(prop);
              obj[prop].apply(obj, args);
            };
      },
    };
    return new Proxy(this, handler);
  }

  middleware(prop) {
    console.log(`Executing function ${prop}`);
  }

  a() {}

  b() {}

  c() {}
}

const obj = new MyClass();

obj.a();
obj.b();
obj.c();
like image 143
Guerric P Avatar answered Oct 11 '22 04:10

Guerric P