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

前端 未结 8 1015
广开言路
广开言路 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 05:08

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

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

    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

    0 讨论(0)
提交回复
热议问题