719-286-0751 [email protected]

How to Get Object or Function from String

When using Javascript sometimes we need to map a literal string: “My.Nested.Class” to the corresponding object or class.

Below I’ve provided an easy function to determine this, utilizing the underscorejs library. Essentially, this function takes a literal string and an optional “context” argument. The context argument can be used to localalize the object search to a property other than the global “window.” This solution is more efficient than using eval to get the class object from a string.

The function works by iterating over each component of the given string, using “.” as the delimiter. So for example: stringToObject(“My.Object”) works as follows:

  1. Search for window[My] – if we don’t find a result, return null;
  2. Search for window[My][Object] – if we find a result return it, otherwise return null

    stringToObject = function (path, context) {
        var target,
        pathSeparator = '.',
        scopes = [context || window];
        for (var ctx, i = 0, l = scopes.length; i < l; ++i) {
            if (ctx = scopes[i]) {
                target = _.reduce(path.split(pathSeparator), function (memo, elem) {
                    return memo[elem];
                }, ctx);
                if (target) break;
        return target;
Alan Barber is the Lead Web Developer at Cadence Labs and a Magento Certified developer.

Submit a Comment

Your email address will not be published. Required fields are marked *

Install our webapp on your iPhone! Tap and then Add to homescreen.
Share This