JavaScript – Create Dynamic JavaScript Functions through Function Constructor

A JavaScript function can be created with Function constructor like followings:

// Create a function that takes two arguments and returns the sum of those arguments
var adder = new Function('a', 'b', 'return a + b');

// Call the function
adder(5, 3);
// > 8

In the above example adder is now a function. However there are 2 points I would like to highlight.

1. Calling the constructor directly can create functions dynamically, but suffers from security and performance issues similar to eval.

2. JavaScript functions created with Function constructor is always in 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.

var x = 10;

function createFunctionOne() {
    var x = 20;
    return new Function('return x;'); // this |x| refers global |x|

function createFunctionTwo() {
    var x = 20;
    function f() {
        return x; // this |x| refers local |x| above
    return f;

var f1 = createFunctionOne();
console.log(f1());          // 10
var f2 = createFunctionTwo();
console.log(f2());          // 20

Author: Wu Chia Chong

My main areas of interest are software architectures and software design methods, patterns, and new trends in software development.