/ Published in: JavaScript
Runtime Object Evaluator; search for string object properties that start with !! and eval the content.
Very useful if you want to load JSON from file and evaluate its fields on effective usage or access global variables at runtime.
[Follow me on Twitter for updates](http://twitter.com/fstraps/ "fstraps on Twitter")
Very useful if you want to load JSON from file and evaluate its fields on effective usage or access global variables at runtime.
[Follow me on Twitter for updates](http://twitter.com/fstraps/ "fstraps on Twitter")
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * Usage: * var o={a:1, b:'!! 1+1', c:'!! alert(\'c\')'}; * evalObj(o); * //o.a===1 * //o.b===2 * //o.c() will display an alert * * Updated to keep the scope, usage: * var o={a:1, b:'!! this.a+1', c:'!! alert(this.b+1)'}; * evalObj.call(o,o); * //o.a===1 * //o.b===2 * //o.c() will display an alert with 3 * */ function evalObj(o,rec){ if (rec === undefined) { rec=true; } for (var name in o){ var elem=o[name]; if (elem){ var telem=typeof elem; if (telem==='string' && /^!!/.test(elem)){ o[name]=new Function('return '+elem.substr(2)).call(this); }else if (rec && telem==='object'){ evalObj.call(this,elem,rec); } } } return o; }
URL: http://straps.tumblr.com/post/146642767/evalobj