1

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.

bleuthoot
  • 75
  • 1
  • 7

3 Answers3

0

Following Function document link, you should define function just from code lines, not include something like function XXXXX() {}

So, it should be

let blocklyResult = `console.log('Function has been called!')`;
let code = new Function(blocklyResult);

code()
matsev
  • 32,104
  • 16
  • 121
  • 156
Dat Ho
  • 694
  • 3
  • 10
0

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();
Yosef Tukachinsky
  • 5,570
  • 1
  • 13
  • 29
0
let blocklyResult = `function onExecute() {
    console.log('Function has been called!');
}`;

// v1
let code1 = new Function(`${blocklyResult};onExecute();`);
code1();

// v2
let code2 = (new Function(`return ${blocklyResult}`))();
code2();

v1 creates a new function every time it's called

v2 returns the function so it can be called multiple times without recreating the blockly function

v2 is preferable IMO

flcoder
  • 713
  • 4
  • 14