Creating functions dynamically in JS

To extend Ericks answer about the Function constructor.

The Function constructor creates an anonymous function, which on runtime error would print out anonymous for each function (created using Function) in the call stack. Which could make debugging harder.

By using a utility function you can dynamically name your created functions and bypass that dilemma. This example also merges all the bodies of each function inside the functions array into one before returning everything as one named function.

const _createFn = function(name, functions, strict=false) {

    var cr = `\n`, a = [ 'return function ' + name + '(p) {' ];

    for(var i=0, j=functions.length; i<j; i++) {
        var str = functions[i].toString();
        var s = str.indexOf(cr) + 1;
        a.push(str.substr(s, str.lastIndexOf(cr) - s));
    }
    if(strict == true) {
        a.splice(1, 0, '\"use strict\";' + cr)
    }
    return new Function(a.join(cr) + cr + '}')();
}

A heads up about the Function constructor:

A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#Differences


Well, you could use Function constructor, like in this example:

var f = new Function('name', 'return alert("hello, " + name + "!");');
f('erick');

This way you're defining a new function with arguments and body and assigning it to a variable f. You could use a hashset and store many functions:

var fs = [];
fs['f1'] = new Function('name', 'return alert("hello, " + name + "!");');
fs['f1']('erick');

Loading xml depends if it is running on browser or server.

Tags:

Javascript