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

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

提交回复
热议问题