Given a string classname
, I want to dynamically create a new JavaScript function named after that string that can be used to instantiate objects.
I\'ve
function registerFunction(functionBody) {
"use strict";
var script = document.createElement("script");
script.innerHTML = "function " + functionBody;
document.body.appendChild(script);
}
registerFunction("fooBar(x, y) { return x + y; }");
fooBar(1, 2); // will give you 3
Although this is essentially the same as eval()
but it will register the function in the domain of the current page. You can later remove this script element, or reuse it for other functions.