JS: Call certain function before calling each of other functions in file
You could use a Proxy
where the target is one object with all of your functions, and then you could use get
trap to catch every function call from that proxy. Then instead of exporting each function you could just export that proxy object.
const a = (paramA, paramB) => console.log('a', paramA, paramB)
const b = () => console.log('b')
const c = () => console.log('c')
const foo = () => console.log('Foo')
const functions = new Proxy({a, b, c}, {
get() {
foo();
return Reflect.get(...arguments);
}
})
functions.a('foo', 'bar')
functions.c()
If you want to catch called function arguments and pass those arguments to foo
you could return a proxy function from the get method where you have access to provided arguments and then inside you call foo and called function.
const a = (paramA, paramB) => console.log('a', paramA, paramB)
const b = () => console.log('b')
const c = () => console.log('c')
const foo = (...params) => {
console.log('Foo', params)
}
const functions = new Proxy({a, b, c}, {
get(target, prop) {
return function(...params) {
foo(...params);
target[prop].apply(null, params)
}
}
})
functions.a('foo', 'bar')
functions.c('baz')
You can use classes, extend Foo
and run a super() on the constructor.
class Foo {
constructor(){
//do something
}
}
export class A extends Foo {
constructor(){
super();
}
}
export class B extends Foo {
constructor(){
super();
}
}
But all in all, it's almost just the same as calling Foo()
over and over again. You still have to explicitly write the super and extends for each function.
But what if i have more then 3 function? How to optimise foo() function calls and call it each time before each file functions are called?
There is just no issues calling Foo()
for each function. It's not like you are dynamically creating your function and have to find a way to decorate it somehow.
But hey you can add all your functions into an iterable and decorate foo()
on them before you export.
const foo = ()=>{ console.log('foo') }
const a = ()=>{console.log('a');}
const b = ()=>{console.log('b')}
const c = ()=>{console.log('c')}
//make sure to create the collection which we will iterate later on.
//you can also implicitly add the functions here instead
const collection = {a, b, c};
//this runs at the bottom of the script
const obj = {};
for(let col in collection){
obj[col] = function(f){
return (args) => {
foo(args); f(args);
}
}(collection[col]);
}
//then export
export obj;