javascriptblocklygoogle-blockly

Calling function within a Function


I have a situation where I generate code from within a Blockly component. The resulting code will have a function that I want to call. According to the Blockly "Generating and Running JavaScript" documentation, I should use eval().

When I look up eval() on MSDN, I get a section that I should "never use eval" and use Function instead.

Here is some example code from what the output of the code could be:

let blocklyResult = `function onExecute() {
    console.log('Function has been called!');
}`;

let code = new Function(blocklyResult);

I want to call the onExecute function from within the code variable, but I cannot figure out how I can do that?

What is the best way to accomplish my desired result.


Solution

  • the Function constructor will generate a function with the string code inside. if the string code come in format of function, the function will generate this function, but you also need to call it. So ether (if you can) pass as a string the code to execute (not function) or add execute the function yourself. like this:

    var a = `function onExecute(){console.log('Function has been called')}`
    var b = new Function(`(${a})()`);
    b();