I am trying to pass a custom function named callpaul() into the scope of the Function constructor so that the function can be called inside the scope of Function. According to the MDN docs it seems like this should work, what am I doing wrong?
let fil={}
let trans={val:"fil.res=[1,2].join('&')"}
console.log(`WORKS------`)
Function('fil', '"use strict";return (' trans.val ')')(fil);
console.log({fil})
console.log(`FAILS-----`)
trans={val:"fil.res=callpaul('a')"}
Function('callpaul','fil', '"use strict";return (' trans.val ')')(`function callpaul (p){return 'hi' p}`,fil);
console.log({fil})
CodePudding user response:
You are not using the Function constructor correctly - the first arguments will be the names of the parameters within the newly created argumented. I have renamed some variables to make it more understandable (the first param is the function being passed it, and the second param is where the result is stored into) and it now works.
console.log(`FAILS-----`) //now actually works
trans={val:"output.res=passedFunction('a')"}
//Define the new function and store it in newfunc
let newfunc = Function('passedFunction','output', '"use strict";return (' trans.val ')');
//Call the new function, passing in your callpaul function to be called, and fil to hold the result
newfunc( function callpaul (p){return 'hi' p;}, fil) );
console.log({fil});
CodePudding user response:
You are not passing the callpaul function as an argument to the Function constructor. The Function constructor only accepts strings representing the source code of the function. To pass the custom function callpaul as an argument to Function, you need to pass it as a string. You can do this by converting the function to a string using .toString(). Here is an updated example:
let fil = {};
let trans = {val: "fil.res = [1,2].join('&')"};
console.log(`WORKS------`);
Function('fil', '"use strict";return (' trans.val ')')(fil);
console.log({fil});
console.log(`FAILS-----`);
trans = {val: "fil.res = callpaul('a')"};
Function('callpaul', 'fil', '"use strict";return (function callpaul (p){return "hi" p}.toString() trans.val)')(fil);
console.log({fil});