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

前端 未结 8 1057
广开言路
广开言路 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.

提交回复
热议问题