1

I have to work with strings to execute functions. So I created a new function where i put the string. It works but not when I want to call a specific function in another module :

var mymodule = require('./mymodule');

...

mymodule.function(a, b); //Works

var functionTest1= new Function('var a = 2; console.log(a*a);');  
functionTest1(); //Works

var functionTest2= new Function('mymodule.function(a, b)');
functionTest2(); //Doesn't work (error console : mymodule is not defined)

What am I doing wrong? Is there an other way to do it ?

13
  • Why are you trying to do this? I have to work with strings to execute functions. Why? Commented Oct 18, 2017 at 14:30
  • Because the string come from a module which is an observer. So if I want in the futur another behavior i just have to add another module observer and write a new function with a string. (I don't know if it's the best idea but i found this flexible) Commented Oct 18, 2017 at 14:44
  • Your example works completely fine for me in the node REPL. I accidentally reproduced your error by mis-typing mymodule as myModule. Perhaps it was just a typo? Commented Oct 18, 2017 at 14:44
  • 1
    @chriskelly: it probably worked in the repl because everything in the repl is in global scope. But if you are inside a module, Imports are module scoped, whereas functions created with the Function constructor are declared in global scope. Commented Oct 18, 2017 at 15:42
  • 1
    Using the function constructor is likely the wrong approach. If you’d provide a more complete example we could probably suggest a better solution. Commented Oct 18, 2017 at 15:43

1 Answer 1

1

Please try this:

var functionTest3 = new Function('mymodule','a','b', 'mymodule.function(a, b)');
functionTest3(mymodule, a, b);

Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called.

More to read here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function

Sign up to request clarification or add additional context in comments.

2 Comments

You might want to explain why this works and/or what the problem with the OPs code is.
@Felix Kling yeah, sure

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.