0

Is it possible to call a function in javascript from a string, where the function is in an object?

e.g: call "main.object.doSomething()" (notice it is a string) from the object below.

window.main = {
    object: {
        doSomething: function(){
            alert('Called');
       }
    }
}

--- Update ---

...without using eval();

DJ Mosca
  • 240
  • 1
  • 2
  • 6

5 Answers5

2
window.main = {
    object: {
        doSomething: function(){
            alert('Called');
       }
    }
}

function callFromString(aString) {
  var parts = aString.split(".");
  var obj = window;
  for (var i = 0; i < parts.length - 1; i++) {
    obj = obj[parts[i]];
    if (!obj)
      return;
  }
  // strip () at the end of parts[parts.length - 1] if they are present
  if (obj[parts[parts.length - 1]])
    obj[parts[parts.length - 1]]();
}

callFromString("main.object.doSomething");

http://jsfiddle.net/79nWH/

Igor
  • 15,833
  • 1
  • 27
  • 32
1

You can use eval, so:

eval("main.object.doSomething()");

But eval is evil - try to avoid it.

hsz
  • 148,279
  • 62
  • 259
  • 315
1

Do not use eval! There are many good reasons not to use eval, and most of the time there's absolutely no reason to do so. Instead, you can use the string property lookup syntax to get the method you're looking for: main.object.doSomething() is equivalent to main.object['doSomething'](). So, for example, if you want to call a function based on a string, you could do:

var methodToCall = 'doSomething';
main.object[methodToCall]();

If putting the parentheses right after the property lookup looks weird to you, you could also do main.object[methodToCall].call(null).

Community
  • 1
  • 1
OverlappingElvis
  • 621
  • 6
  • 20
0

use eval(expression or function)

read about that in http://www.w3schools.com/jsref/jsref_eval.asp or http://viralpatel.net/blogs/calling-javascript-function-from-string/

Carlos Cocom
  • 937
  • 1
  • 8
  • 23
0

Lets say you have your string like:

var funcString = "window.main = {
    object: {
        doSomething: function(){
            alert('Called');
       }
    }
}";
eval(funcString);

and if you have already your function defined in the page, you can call it with 2 different ways, using eval (which no js expert would never offer using it, you should use it just when you don't have any other option):

eval("main.object.doSomething()");

and the other way is using anonymous function:

Function("main.object.doSomething();")();
Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35