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.
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.
The setInterval() method repeats a given function at every given time-interval.
var test = new MyObject(); and then do this: test. myMethod();
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.
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();
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