将字符串(曾经是一个函数)转换回 Javascript 中的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10901217/
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
Convert string (was a function) back to function in Javascript
提问by Robert
I have this function below as a string. How would I convert it back into a function? I am pulling event handlers from JQuery events and I want to store them as string then convert them back because they will be saved in mySQL
我在下面有这个函数作为字符串。我如何将其转换回函数?我正在从 JQuery 事件中提取事件处理程序,我想将它们存储为字符串,然后将它们转换回来,因为它们将保存在 mySQL 中
function () {
if (!GActiveClick) {
return;
}
SaveProduct();
}
回答by gdoron is supporting Monica
var func = new Function(theFunctionString);
func();
MDN:
目录:
new Function ([arg1[, arg2[, ... argN]],] functionBody)
Parameters
arg1, arg2, ... argN
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".functionBody
A string containing the JavaScript statements comprising the function definition.
新函数 ([arg1[, arg2[, ... argN]],] 函数体)
参数
arg1, arg2, ... argN
函数用作形式参数名称的名称。每个必须是一个与有效 JavaScript 标识符相对应的字符串或用逗号分隔的此类字符串列表;例如“x”、“theValue”或“a,b”。functionBody
一个字符串,其中包含构成函数定义的 JavaScript 语句。
Update:
更新:
All this a verybad practice!
You should have a generic function that get parameters that build what you want. The only thing that change are the parameters. Store those parameters in the DB you have.
所有这些都是非常糟糕的做法!
您应该有一个通用函数来获取构建您想要的参数的参数。唯一改变的是参数。将这些参数存储在您拥有的数据库中。
回答by Fernando Carvajal
Use the return
when using new Function()
and execute it, like this
使用return
时使用new Function()
并执行它,像这样
new Function('return ' + fn_string)();
Example:
例子:
function hackerAll(a, b) {
var result = a*b
return result
}
class Doggy{
method1(){
return 123123*342343
}
}
var fn_string = hackerAll.toString()
var back_to_fn = new Function(`return ${fn_string}`)() //This restore the function with name, params and all, even es7 class works
var class_string = Doggy.toString()
var back_to_class = new Function(`return ${class_string}`)()
console.log('fn as it', hackerAll)
console.log('fn string', fn_string)
console.log('restored fn', back_to_fn)
console.log('restored class', back_to_class)
回答by user1434045
Javascript provides the new- keyword for functions
Javascript 为函数提供了 new- 关键字
var foo = new Function("arg", ... , "<implementation string>");
see here for example... http://www.permadi.com/tutorial/jsFunc/
例如,请参见此处... http://www.permadi.com/tutorial/jsFunc/