new Function() does not work as expected

Posted on
  • Hello,

    when I execute the following code in the browser or in Node.js, I see the console log with the value 4. In Espruino nothing happens. Do you have an idea why?

    var x = new Function([ 'a' ], 'console.log(a);');
    x.apply({}, [ 4 ]);
    

    Best,

    Tobias

  • Hi Tobias,

    I've just checked, and it's an issue with Espruino's implementation of the Function constructor. Basically it only looks for the code to run, and not for the optional list of arguments.

    So (new Function('console.log("Hello");'))() will work, but you won't be able to supply arguments.

    I've filed a bug for it here: https://github.com/espruino/Espruino/iss­ues/505

    If you want to work around it you could do:

    function newFunction(args, code) {
      return eval("(function("+args.join(",")+"){"+co­de+"})");
    }
    var x = newFunction([ 'a' ], 'console.log(a);');
    x.apply({}, [ 4 ]);
    
  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

new Function() does not work as expected

Posted by Avatar for net-tobi @net-tobi

Actions