I have a function which takes a function as an argument write(fn) {...}
.
I would like to manipulate the function’s execution and execute some statements while proxying its arguments. Here is my code idea:
...
const handler = {
apply(target, thisArg, argumentsList) {
let params = getParamNames(target);
let statements = splitFunctionContent(target);
statements.forEach((statement) => {
let placeholders = refreshPlaceholders(params);
// Create a function with placeholders as parameters
const func = new Function(...Object.keys(placeholders), statement);
// Execute the function with placeholders as arguments
func(...Object.values(placeholders));
console.log(result);
result = "";
});
}
};
// Create a proxy for `fn` with the handler
const p = new Proxy(fn, handler);
// Call the proxied function
p();
The above handling is giving a reference error, whenever there is a functioncall of a function inside the proxied function. This means that, as expected very well, the current scope of the function defined by new Function
is different than the original’s fn
‘s scope.
I would like to execute every statement within fn
‘s scope. Any idea how to do that ?
One way of dealing with this is to execute:
target.apply(thisArg, argumentsList);
But with this, we don’t have the freedom in deciding which statement to execute.
How to achieve my goal in defining either of the following:
- Either define a function (just like I am doing) that has the same scope as fn (i.e, it sees all the variables that
fn
itself sees). - Make
fn
execute a very specific statement within it (Since fn itself is executing it, we have no scope problem).