给定一个描述Javascript函数的字符串,将其转换为Javascript函数

时间:2022-09-13 12:20:24

Say I've got a Javascript string like the following

说我有一个类似下面的Javascript字符串

var fnStr = "function(){blah1;blah2;blah3; }" ;

(This may be from an expression the user has typed in, duly sanitized, or it may be the result of some symbolic computation. It really doesn't matter).

(这可能来自用户输入的表达式,正确消毒,或者可能是某些符号计算的结果。这无关紧要)。

I want to define fn as if the following line was in my code:

我想定义fn,好像我的代码中有以下行:

var fn = function(){blah1;blah2;blah3; } ;

How do I do that?

我怎么做?

The best I've come up with is the following:

我提出的最好的是以下内容:

var fn = eval("var f = function(){ return "+fnStr+";}; f() ;") ;

This seems to do the trick, even though it uses the dreaded eval(), and uses a slightly convoluted argument. Can I do better? I.e. either not use eval(), or supply it with a simpler argument?

这似乎可以解决问题,即使它使用了可怕的eval(),并使用了一个稍微复杂的参数。我可以做得更好吗?即要么不使用eval(),要么提供更简单的参数?

8 个解决方案

#1


49  

There's also the Function object.

还有Function对象。

var adder = new Function("a", "b", "return a + b");

#2


23  

You can do this:

你可以这样做:

//in your case: eval("var fn = " + fnStr);
eval("var fn = function(){ blah1;blah2;blah3; }"); 
fn();

Not sure how to get it much simpler, sometimes there's no (better) way around eval(). Here's a quick example of this in action.

不知道如何更简单,有时没有(更好)的方式围绕eval()。这是一个很好的例子。

#3


11  

Use parentheses.

var fn = eval("(function() {...})");

This technique is also good for transmitting JSON values.

此技术也适用于传输JSON值。

By the way, it's often better to build functions by composing them directly from other functions. If you are using strings, you have to worry about things like unexpected variable capture.

顺便说一下,通过直接从其他函数编写函数来构建函数通常更好。如果您使用字符串,则必须担心意外变量捕获等问题。

#4


3  

The Function constructor creates a new Function object. In JavaScript every function is actually a Function object.

Function构造函数创建一个新的Function对象。在JavaScript中,每个函数实际上都是一个Function对象。

// Create a function that takes two arguments and returns the sum of those arguments
var fun = new Function("a", "b", "return a + b");
// Call the function
fun(2, 6);
Output: 8

#5


3  

You can also insert the string into a script element and then insert the script element into the page.

您还可以将字符串插入到脚本元素中,然后将脚本元素插入到页面中。

script_ele = window.document.createElement("script");
script_ele.innerHTML = 'function my_function(){alert("hi!");}';
window.document.body.appendChild(script_ele);
my_function();

#6


2  

one way:

     var a = 'function f(){ alert(111); } function d(){ alert(222);}';  
     eval(a);
     d();

second more secure way to convert string to a funciton:

将字符串转换为函数的第二种更安全的方法:

     // function name and parameters to pass
    var fnstring = "runMe";
    var fnparams = ["aaa", "bbbb", "ccc"];

    // find object
    var fn = window[fnstring];

    // is object a function?
    if (typeof fn === "function") fn.apply(null, fnparams);


    function runMe(a,b){
      alert(b);
    }

look working code http://plnkr.co/edit/OiQAVd9DMV2PfK0NG9vk

看看工作代码http://plnkr.co/edit/OiQAVd9DMV2PfK0NG9vk

#7


2  

Here's what I use for simple cases:

这是我用于简单案例的内容:

// an example function
function plus(...args) {
    return args.reduce( (s,v) => s+v, 0 );
}

// function to string
let str = plus.toString();

// string to function
let copy = new Function('return ' + str)();

// tests
console.assert(plus.name == 'plus');
console.assert(copy.name == 'plus');
console.assert(plus.constructor == Function);
console.assert(copy.constructor == Function);
console.assert(plus(1,2,3,4) === copy(1,2,3,4));
console.assert(plus.toString() === copy.toString());

#8


1  

You can call Parse your string as javascript fuction

你可以调用解析你的字符串作为javascript功能

  1. function getDate(){alert('done')} // suppose this is your defined function
  2. function getDate(){alert('done')} //假设这是你定义的函数

to call above function getDate() is this in string format like 'getDate()'

调用上面的函数getDate()是字符串格式,如'getDate()'

  1. var callFunc=new Function('getDate()') //Parse and register your function

    var callFunc = new Function('getDate()')//解析并注册你的函数

  2. callFunc() // Call the function

    callFunc()//调用函数

#1


49  

There's also the Function object.

还有Function对象。

var adder = new Function("a", "b", "return a + b");

#2


23  

You can do this:

你可以这样做:

//in your case: eval("var fn = " + fnStr);
eval("var fn = function(){ blah1;blah2;blah3; }"); 
fn();

Not sure how to get it much simpler, sometimes there's no (better) way around eval(). Here's a quick example of this in action.

不知道如何更简单,有时没有(更好)的方式围绕eval()。这是一个很好的例子。

#3


11  

Use parentheses.

var fn = eval("(function() {...})");

This technique is also good for transmitting JSON values.

此技术也适用于传输JSON值。

By the way, it's often better to build functions by composing them directly from other functions. If you are using strings, you have to worry about things like unexpected variable capture.

顺便说一下,通过直接从其他函数编写函数来构建函数通常更好。如果您使用字符串,则必须担心意外变量捕获等问题。

#4


3  

The Function constructor creates a new Function object. In JavaScript every function is actually a Function object.

Function构造函数创建一个新的Function对象。在JavaScript中,每个函数实际上都是一个Function对象。

// Create a function that takes two arguments and returns the sum of those arguments
var fun = new Function("a", "b", "return a + b");
// Call the function
fun(2, 6);
Output: 8

#5


3  

You can also insert the string into a script element and then insert the script element into the page.

您还可以将字符串插入到脚本元素中,然后将脚本元素插入到页面中。

script_ele = window.document.createElement("script");
script_ele.innerHTML = 'function my_function(){alert("hi!");}';
window.document.body.appendChild(script_ele);
my_function();

#6


2  

one way:

     var a = 'function f(){ alert(111); } function d(){ alert(222);}';  
     eval(a);
     d();

second more secure way to convert string to a funciton:

将字符串转换为函数的第二种更安全的方法:

     // function name and parameters to pass
    var fnstring = "runMe";
    var fnparams = ["aaa", "bbbb", "ccc"];

    // find object
    var fn = window[fnstring];

    // is object a function?
    if (typeof fn === "function") fn.apply(null, fnparams);


    function runMe(a,b){
      alert(b);
    }

look working code http://plnkr.co/edit/OiQAVd9DMV2PfK0NG9vk

看看工作代码http://plnkr.co/edit/OiQAVd9DMV2PfK0NG9vk

#7


2  

Here's what I use for simple cases:

这是我用于简单案例的内容:

// an example function
function plus(...args) {
    return args.reduce( (s,v) => s+v, 0 );
}

// function to string
let str = plus.toString();

// string to function
let copy = new Function('return ' + str)();

// tests
console.assert(plus.name == 'plus');
console.assert(copy.name == 'plus');
console.assert(plus.constructor == Function);
console.assert(copy.constructor == Function);
console.assert(plus(1,2,3,4) === copy(1,2,3,4));
console.assert(plus.toString() === copy.toString());

#8


1  

You can call Parse your string as javascript fuction

你可以调用解析你的字符串作为javascript功能

  1. function getDate(){alert('done')} // suppose this is your defined function
  2. function getDate(){alert('done')} //假设这是你定义的函数

to call above function getDate() is this in string format like 'getDate()'

调用上面的函数getDate()是字符串格式,如'getDate()'

  1. var callFunc=new Function('getDate()') //Parse and register your function

    var callFunc = new Function('getDate()')//解析并注册你的函数

  2. callFunc() // Call the function

    callFunc()//调用函数