Posted By

axolx on 12/31/10


Tagged


Versions (?)

Javascript String to Function


 / Published in: JavaScript
 

URL: http://stackoverflow.com/questions/1366127/instantiate-a-javascript-object-using-a-string-to-define-the-class-name

  1. /**
  2.  * Accepts a namespaced variable pointing to a class and returns a constructor
  3.  * for that class.
  4.  *
  5.  * @see http://stackoverflow.com/questions/1366127/instantiate-a-javascript-object-using-a-string-to-define-the-class-name
  6.  */
  7.  
  8. stringToFunction = function(str) {
  9. var arr = str.split(".");
  10.  
  11. var fn = (window || this);
  12. for ( var i = 0, len = arr.length; i < len; i++) {
  13. fn = fn[arr[i]];
  14. }
  15.  
  16. if (typeof fn !== "function") {
  17. throw new Error("function not found");
  18. }
  19.  
  20. return fn;
  21. };

Report this snippet  

You need to login to post a comment.