Risposte:
Ho aggiunto un test jsperf per 4 diversi modi per creare una funzione dalla stringa:
Utilizzo di RegExp con la classe Function
var func = "function (a, b) { return a + b; }".parseFunction();
Utilizzo della classe Function con "return"
var func = new Function("return " + "function (a, b) { return a + b; }")();
Utilizzo del costruttore di funzioni ufficiale
var func = new Function("a", "b", "return a + b;");
Utilizzando Eval
eval("var func = function (a, b) { return a + b; };");
Un modo migliore per creare una funzione da una stringa è usare Function
:
var fn = Function("alert('hello there')");
fn();
Ciò ha come vantaggio / svantaggio che le variabili nell'ambito corrente (se non globali) non si applicano alla funzione appena costruita.
È anche possibile passare argomenti:
var addition = Function("a", "b", "return a + b;");
alert(addition(5, 3)); // shows '8'
Function
te non inquini l'ambito locale ed è per questo che eval
rende l'ottimizzazione così difficile per i motori ... Con l'esempio OP, vorrei:var fnc = Function('return '+s)();
element.onclick = function() { alert("test"); }
.
Sei abbastanza vicino.
//Create string representation of function
var s = "function test(){ alert(1); }";
//"Register" the function
eval(s);
//Call the function
test();
Ecco un violino funzionante .
eval
Avviso obbligatorio per i futuri ricercatori: eval
può aprire scappatoie per gli hacker: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… ma se conosci i suoi pericoli e puoi evitarli, allora questo è un bel modo semplice per creare una funzione da una stringa
Sì, l'utilizzo Function
è un'ottima soluzione, ma possiamo andare un po 'oltre e preparare un parser universale che analizza la stringa e convertirla in una vera funzione JavaScript ...
if (typeof String.prototype.parseFunction != 'function') {
String.prototype.parseFunction = function () {
var funcReg = /function *\(([^()]*)\)[ \n\t]*{(.*)}/gmi;
var match = funcReg.exec(this.replace(/\n/g, ' '));
if(match) {
return new Function(match[1].split(','), match[2]);
}
return null;
};
}
esempi di utilizzo:
var func = 'function (a, b) { return a + b; }'.parseFunction();
alert(func(3,4));
func = 'function (a, b) { alert("Hello from function initiated from string!"); }'.parseFunction();
func();
ecco jsfiddle
JavaScript
Function
var name = "foo";
// Implement it
var func = new Function("return function " + name + "(){ alert('hi there!'); };")();
// Test it
func();
// Next is TRUE
func.name === 'foo'
Fonte: http://marcosc.com/2012/03/dynamic-function-names-in-javascript/
eval
var name = "foo";
// Implement it
eval("function " + name + "() { alert('Foo'); };");
// Test it
foo();
// Next is TRUE
foo.name === 'foo'
sjsClass
https://github.com/reduardo7/sjsClass
Class.extend('newClassName', {
__constructor: function() {
// ...
}
});
var x = new newClassName();
// Next is TRUE
newClassName.name === 'newClassName'
Questa tecnica potrebbe essere in definitiva equivalente al metodo eval, ma volevo aggiungerla, poiché potrebbe essere utile per alcuni.
var newCode = document.createElement("script");
newCode.text = "function newFun( a, b ) { return a + b; }";
document.body.appendChild( newCode );
Funzionalmente è come aggiungere questo elemento <script> alla fine del documento, ad esempio:
...
<script type="text/javascript">
function newFun( a, b ) { return a + b; }
</script>
</body>
</html>
Usa il new Function()
con un ritorno all'interno ed eseguilo immediatamente.
var s = `function test(){
alert(1);
}`;
var new_fn = new Function("return " + s)()
console.log(new_fn)
new_fn()
Un esempio con argomenti dinamici:
let args = {a:1, b:2}
, fnString = 'return a + b;';
let fn = Function.apply(Function, Object.keys(args).concat(fnString));
let result = fn.apply(fn, Object.keys(args).map(key=>args[key]))