Skip to content

Instantly share code, notes, and snippets.

@steventux
Created January 4, 2012 12:49
Show Gist options
  • Save steventux/1559909 to your computer and use it in GitHub Desktop.
Save steventux/1559909 to your computer and use it in GitHub Desktop.
Turns a Javascript string into a function, can handle namespaced/contextual functions.
/**
* Given the String "Foo.who.bar" this function returns the function bar() from the context of Foo.who
* handy when you need to call or apply a namespaced function from a String representation.
*/
var stringToFunction = function(str) {
var nsArr = str.split("."),
parentNs = window,
len = nsArr.length;
for (var idx = 0; idx < len; idx++) {
parentNs = parentNs[nsArr[idx]];
}
return parentNs;
}
// E.g. stringToFunction("Foo.who.bar").call(window, args);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment