Kruwe
Kruwe

Reputation: 23

Call a function with a Function object node.js

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 ?

Upvotes: 1

Views: 70

Answers (1)

Iurii Drozdov
Iurii Drozdov

Reputation: 1755

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

Upvotes: 1

Related Questions