In JavaScript, can I check to see if a string can be evaluated without actually evaluating it? -
i attempting write function convert function. function should work follows:
- check see if function , if returns it.
- check see if string , if there global function name, if return that.
- check see if string can evaluated , if return lambda (anonymous) function evaluates string.
- if previous attempts convert value function fail, return lambda (anonymous) function returns value. how handle other variable types (numbers, null, undefined, boolean, objects , arrays).
function caneval(str){ try { eval(str); } catch (e){ return false; } return true; } function tofunc(v){ if(typeof(v) == "function") return v; if(typeof(v) == "string"){ if( window[v] != undefined && typeof(window[v]) == "function" ) return window[v]; if(caneval(v)) return function(){eval(v)}; } return function(){return v;}; };
the problem code caneval
evaluates code, in circumstances not want code (in string) run more once. evaluates string see if there errors, , if not returns evaluated code (string) function, ran again @ later date.
is there way can test see if code can evaluated (without errors) without running code? or run isolated happens in evaluated code (string) doesn't take affect on current file?
someone posted answer worked removed it. here working tofunc
works described.
function tofunc(v){ if(typeof(v) == "function") return v; if(typeof(v) == "string"){ if( window[v] != undefined && typeof(window[v]) == "function" ) return window[v]; try { return new function(v); }catch(e){} } return function(){return v;}; };
the answer use function
constructor within try-catch statement
Comments
Post a Comment