1

I want to programmatically reach a method that is nested inside a object.

var app = {
    property:{
        method:function(){},
        property:"foo"
    }    
}

Normally you would access it like so: app.property.method

But in my case, In runtime I get a string that I want to interpolate that into calling the method function

Now, how can method be accessed programmatically when i have the following string

"app.property.method"       

​ For a reference please see: http://jsfiddle.net/adardesign/92AnA/

adardesign
  • 33,973
  • 15
  • 62
  • 84

3 Answers3

2

You'd need to use bracket notation (i'd avoid the other option - eval()). If the app variable is global, then it would be a property of the window object:

executeFunctionByName("app.property.method", window);

Method borrowed from: How to execute a JavaScript function when I have its name as a string

The method essentially just breaks your window["app.property.method"] (which would fail) into window["app"]["property"]["method"] (which works).

Community
  • 1
  • 1
jbabey
  • 45,965
  • 12
  • 71
  • 94
2

A while ago I wrote this little script to get an object from the string describing its path:

(function () {
    "use strict";
    if (!Object.fromPath) {
        Object.fromPath = function (context, path) {
            var result,
                keys,
                i;
            //if called as `Object.fromPath('foo.bar.baz')`,
            //assume `window` as context
            if (arguments.length < 2) {
                path = context;
                context = window;
            }
            //start at the `context` object
            result = context;
            //break the path on `.` characters
            keys = String(path).split('.');
            //`!= null` is being used to break out of the loop
            //if `null` or `undefined are found
            for (i = 0; i < keys.length && result != null; i+= 1) {
                //iterate down the path, getting the next part
                //of the path each iteration
                result = result[keys[i]];
            }
            //return the object as described by the path,
            //or null or undefined if they occur anywhere in the path
            return result;
        };
    }
}());
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
0

You could try this:

var methodString = "app.property.method";

var method = eval(methodString);

Then method will be a function pointer which may be called like so:

method();
Tim Lamballais
  • 1,056
  • 5
  • 10