I want to create a higher-level function that returns functions in order to be serialized and sent to another machine.
For example I want to create a function that returns Hello world
, by passing world
to a generator function and afterwards serialize by toString:
function returnAnotherFunction(name) {
return () => { return `Hello ${name}`}
}
const helloWorldFunction = returnAnotherFunction('world')
const serializedFunction = helloWorldFunction.toString()
console.log(serializedFunction)
// prints: () => { return `Hello ${name}`}
// I want: () => { return `Hello world`}
Instead, the returned serialized function does still rely on the variable. I need to serialize the function, so I need it without the variable. I am having problems finding the right keywords for a search and am happy with any help!
CodePudding user response:
Since you need to have a string containing a function definition with variables evaluated, that string template literal needs to be evaluated before being part of the function definition of which you need to output the body.
If you print the function definition as you did in your example, the template literal won't be evaluated and will print out as is.
The only way I know of creating a function definition dynamically so that it contains in the body a string that was already evaluted is using eval()
despite it being a strategy NOT RECOMMENDED
Unfortunately I don't know any better method than this to achieve your goal so I will share it for the sake of excercise.
This is a demo:
function returnAnotherFunction(name) {
return eval(`(function(){return 'Hello ${name}';})`);
}
const helloWorldFunction = returnAnotherFunction('world');
const serializedFunction = helloWorldFunction.toString();
console.log(`function body: "${serializedFunction}"`);
console.log(`function returns: "${helloWorldFunction()}"`);