在JavaScript中,通过“ new Function()”创建函数时如何设置函数参数名称?

CodaRuner

尝试通过设置函数中的参数名称new Function(fnBody),以与动态函数体文本变量相关联。

const myFnBody = " return myParam; ";  // dynamic fn-text, expecting 'myParam' variable.
const myFunc = new Function(myFnBody);  // create the function with the body-text.
const myParamVal = "Hello world.";  // setup argument
console.log(myFunc(myParamVal));   // output: undefined, not 'Hello world.' as desired.

控制台输出是undefined因为“ myParam”未链接到函数调用上下文中的第一个参数(arguments [0])。

想要函数将第一个arg(参数[0])分配给“ myParam”参数,如下所示:

const myFunc = function (myParam) { return myParam; }

我需要它来运行以参数名编写的动态代码:类似于CommonJS的“ require”和“ exports”。该代码期望值带有特定的参数/变量名称。

我能想到的最好的方法是通过arguments集合预先设置一个变量,然后添加实际的动态函数文本:

let dynamicFnText = {SOME USER DEFINED FN BODY-TEXT, such as "return myParam;"};
let myFnBody = "";  // start the fn-body as text (string)
myFnBody += "const myParam = arguments[0];";  // prefix a parameter value via the arguments
myFnBody += dynamicFnText;  // append the dynamic fn text, which expects 'myParam' variable.

let myFunc = new Function(myFnBody);
let myParam = "Hello world.";
console.log(myFunc(myParam));  // 'Hello world."

使用eval:是的,我可以使用eval(),例如:

let myFunc = eval("(function (myParam) {" + dynamicFnText + "})");  // fn with 'myParam'

但是,我正在尝试避免使用“邪恶”eval()功能。我是否应该担心eval()以这种方式使用?

我猜我.setParameters()在函数(new Function())实例期待某种方法或类似的东西new Function(paramNamesArray, fnBody)

任何帮助表示赞赏。谢谢。

一定的表现

调用时,除了函数体之外,只需指定参数名称即可new Function

const myFnBody = " return myParam; ";  // dynamic fn-text, expecting 'myParam' variable.
const myFunc = new Function('myParam', myFnBody);  // create the function with the body-text.
const myParamVal = "Hello world.";  // setup argument
console.log(myFunc(myParamVal));

由于这是来自用户的,因此请确保用户提供了函数将接受的new Function参数列表,然后根据需要参数列表中列出它们

我是否应该担心以这种方式使用eval()?

不,您不应该-new Function与一样不安全eval如果您要使用new Function,那么eval(从安全角度来看)您也可以使用,因为它允许执行动态(并且可能是不安全的)代码。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章