Call javascript function encoded in a string -
if put function string this:
var functionstring = function (message) { console.log(message); }.tostring(); is there way convert string function , call it? tried
eval(functionstring) which returns "uncaught syntaxerror: unexpected token", ,
functionstring.call(this, "hi!"); which returns 'undefined not function'.
is possible in javascript?
thanks in advance reply!
edit: point of question function has been converted string using tostring().
console.log(functionstring); returns string: "function (message) {console.log(message);}"
can transform string function , call it? that's problem trying solve. thanks!
your functionstring contains string
"function (message) { console.log(message); }"
evaluating as-is present javascript engine incorrect syntax (there no name function). javascript expects construct function <name>(<params>) { }. alternatively, can use anonymous function (i.e. no name present), parameter or in context of evaluating expression. minimal typical evaluating expression (function() {})() if want fancy, !function() {} ok - exclamation mark in front turns boolean expression requires function evaluation before negating output.
so, in example work:
eval("("+functionstring+")('abc')");
because anonymous function call - javascript can live with.
alternatively, can use brackets, need assign result can use later:
var foo = eval("("+functionstring+")"); foo('ddd'); here little proof / playground learn it: http://jsfiddle.net/exceeder/ydann6b3/
Comments
Post a Comment