Given a string describing a Javascript function, convert it to a Javascript function

前端 未结 8 1009
广开言路
广开言路 2020-11-27 04:38

Say I\'ve got a Javascript string like the following

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

(This may be from an expression the

相关标签:
8条回答
  • 2020-11-27 04:55

    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.

    0 讨论(0)
  • 2020-11-27 04:56

    You can call Parse your string as javascript fuction

    1. function getDate(){alert('done')} // suppose this is your defined function

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

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

    2. callFunc() // Call the function

    0 讨论(0)
  • 2020-11-27 05:01

    Use parentheses.

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

    This technique is also good for transmitting JSON values.

    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.

    0 讨论(0)
  • 2020-11-27 05:01

    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());
    
    0 讨论(0)
  • 2020-11-27 05:04

    There's also the Function object.

    var adder = new Function("a", "b", "return a + b");
    
    0 讨论(0)
  • 2020-11-27 05:07

    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();
    
    0 讨论(0)
提交回复
热议问题