Javascript String to Function


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



Copy this code and paste it in your HTML
  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. };

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.