Object Runtime Fields Evaluator


/ Published in: JavaScript
Save to your folder(s)

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")


Copy this code and paste it in your HTML
  1. /**
  2.  * Usage:
  3.  * var o={a:1, b:'!! 1+1', c:'!! alert(\'c\')'};
  4.  * evalObj(o);
  5.  * //o.a===1
  6.  * //o.b===2
  7.  * //o.c() will display an alert
  8.  *
  9.  * Updated to keep the scope, usage:
  10.  * var o={a:1, b:'!! this.a+1', c:'!! alert(this.b+1)'};
  11.  * evalObj.call(o,o);
  12.  * //o.a===1
  13.  * //o.b===2
  14.  * //o.c() will display an alert with 3
  15.  *
  16. */
  17.  
  18. function evalObj(o,rec){
  19. if (rec === undefined) {
  20. rec=true;
  21. }
  22. for (var name in o){
  23. var elem=o[name];
  24. if (elem){
  25. var telem=typeof elem;
  26. if (telem==='string' && /^!!/.test(elem)){
  27. o[name]=new Function('return '+elem.substr(2)).call(this);
  28. }else if (rec && telem==='object'){
  29. evalObj.call(this,elem,rec);
  30. }
  31. }
  32. }
  33. return o;
  34. }

URL: http://straps.tumblr.com/post/146642767/evalobj

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.