Javascript 有没有办法用javascript从字符串创建函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7650071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to create a function from a string with javascript?
提问by ymutlu
For example;
例如;
var s = "function test(){
alert(1);
}";
var fnc = aMethod(s);
If this is the string, I want a function that's called fnc. And fnc();
pops alert screen.
如果这是字符串,我想要一个名为 fnc 的函数。并fnc();
弹出警报屏幕。
eval("alert(1);")
doesnt solve my problem.
eval("alert(1);")
不能解决我的问题。
采纳答案by phnah
I added a jsperf test for 4 different ways to create a function from string :
我为 4 种不同的方法添加了一个 jsperf 测试来从字符串创建一个函数:
Using RegExp with Function class
var func = "function (a, b) { return a + b; }".parseFunction();
Using Function class with "return"
var func = new Function("return " + "function (a, b) { return a + b; }")();
Using official Function constructor
var func = new Function("a", "b", "return a + b;");
Using Eval
eval("var func = function (a, b) { return a + b; };");
将 RegExp 与 Function 类一起使用
var func = "function (a, b) { return a + b; }".parseFunction();
使用带有“返回”的函数类
var func = new Function("return " + "function (a, b) { return a + b; }")();
使用官方函数构造函数
var func = new Function("a", "b", "return a + b;");
使用评估
eval("var func = function (a, b) { return a + b; };");
回答by Lekensteyn
A better way to create a function from a string is by using Function
:
从字符串创建函数的更好方法是使用Function
:
var fn = Function("alert('hello there')");
fn();
This has as advantage / disadvantage that variables in the current scope (if not global) do not apply to the newly constructed function.
这有一个优点/缺点,即当前范围内的变量(如果不是全局的)不适用于新构造的函数。
Passing arguments is possible too:
也可以传递参数:
var addition = Function("a", "b", "return a + b;");
alert(addition(5, 3)); // shows '8'
回答by James Hill
You're pretty close.
你很接近。
//Create string representation of function
var s = "function test(){ alert(1); }";
//"Register" the function
eval(s);
//Call the function
test();
Here's a working fiddle.
这是一个工作小提琴。
回答by Mr. Pumpkin
Yes, using Function
is a great solution but we can go a bit further and prepare universal parser that parse string and convert it to real JavaScript function...
是的,使用Function
是一个很好的解决方案,但我们可以更进一步,准备通用解析器来解析字符串并将其转换为真正的 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;
};
}
examples of usage:
用法示例:
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();
hereis jsfiddle
这是jsfiddle
回答by Eduardo Cuomo
Dynamic function names in JavaScript
动态函数名 JavaScript
Using Function
使用 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'
Source: http://marcosc.com/2012/03/dynamic-function-names-in-javascript/
来源:http: //marcosc.com/2012/03/dynamic-function-names-in-javascript/
Using eval
使用 eval
var name = "foo";
// Implement it
eval("function " + name + "() { alert('Foo'); };");
// Test it
foo();
// Next is TRUE
foo.name === 'foo'
Using sjsClass
使用 sjsClass
https://github.com/reduardo7/sjsClass
https://github.com/redardo7/sjsClass
Example
例子
Class.extend('newClassName', {
__constructor: function() {
// ...
}
});
var x = new newClassName();
// Next is TRUE
newClassName.name === 'newClassName'
回答by David Newberry
This technique may be ultimately equivalent to the eval method, but I wanted to add it, as it might be useful for some.
这种技术可能最终等同于 eval 方法,但我想添加它,因为它可能对某些人有用。
var newCode = document.createElement("script");
newCode.text = "function newFun( a, b ) { return a + b; }";
document.body.appendChild( newCode );
This is functionally like adding this <script> element to the end of your document, e.g.:
这在功能上类似于将这个 <script> 元素添加到文档的末尾,例如:
...
<script type="text/javascript">
function newFun( a, b ) { return a + b; }
</script>
</body>
</html>
回答by Fernando Carvajal
Use the new Function()
with a return inside and execute it immediately.
使用new Function()
里面有一个 return 并立即执行它。
var s = `function test(){
alert(1);
}`;
var new_fn = new Function("return " + s)()
console.log(new_fn)
new_fn()
回答by brunettdan
An example with dynamic arguments:
带有动态参数的示例:
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]))