Return to Snippet

Revision: 38388
at December 31, 2010 13:15 by axolx


Initial Code
/**
 * Accepts a namespaced variable pointing to a class and returns a constructor
 * for that class.
 * 
 * @see http://stackoverflow.com/questions/1366127/instantiate-a-javascript-object-using-a-string-to-define-the-class-name
 */

stringToFunction = function(str) {
	var arr = str.split(".");

	var fn = (window || this);
	for ( var i = 0, len = arr.length; i < len; i++) {
		fn = fn[arr[i]];
	}

	if (typeof fn !== "function") {
		throw new Error("function not found");
	}

	return fn;
};

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

Initial Description


Initial Title
Javascript String to Function

Initial Tags


Initial Language
JavaScript