I want to define a function:
const f = (outside, param1, param2) => {
outside(param1, param2);
}
But I know this function will always be called inside a function which has outside as parameter. For example:
const g = (outside, param3, param4) => {
// some code here
f(outside, var1, var2);
// some more code
}
Is there any way to define f so that I dont need to pass outside to it when calling inside g?
Also I want to be able to call f inside other functions who take outside as parameter, not just g.
Is there any way to define
fso that I dont need to passoutsideto it when calling insideg?
No. You are asking for dynamic scope but JavaScript uses lexical scope. That means the availability/visibility of symbols is determined by the way functions are defined, not how/when/where they are called.
You can change the order of the arguments and take action depending on their existence:
const f = (param1, param2, outside) => {
if (outside) {
outside(param1, param2);
} else {
...
}
}
UPDATE
Unfortunately a function defined outside of function g, will not have direct access to the variables contained in function g. For this reason, you must necessarily pass the parameter outside to function f.
And if you change your logic like this? Will it fit your needs?
// Set function logic
const f = (param1, param2) => {
return param1 + param2;
}
// Outside method
const outside = v => {
console.log(`I'm outside: ${v}`);
}
// Call from outside logic
const g = (outside, param3, param4) => {
// If you know, that it is outside wrapper, wrap it here
outside(f(param3, param4));
}
g(outside, 2, 2);
// Call from else logic
console.log(`I'm else logic: ${f(3, 3)}`);