0

This code doesn't work:

var my = {
  testFunction: function(text) {
    alert(text);
  }
};

var functionName = "my.testFunction";

var f = window[functionName];

f('yeha');

Any idea why?

Update:

I don't know in advance the functionName. It might be 'my.testFunction' or 'my.test.another.function' etc.

I'm writing a validation handler and all my js will know is a string representing a function that could be a function inside an object.

MojoDK
  • 4,410
  • 10
  • 42
  • 80
  • Do you have a variable named `"my.testFunction"`? – Rajesh Jun 09 '17 at 10:25
  • `eval(functionName + '()')` makes it work. It doesn't now because bracket notation can be used to access only a direct property of an object. – raina77ow Jun 09 '17 at 10:26
  • Vote to close as a question without clear problem statement. posts seeking debug help like Why this code isn't working is off topic here – Sagar V Jun 09 '17 at 10:26
  • The question is: why do you expect using dots in property name in brackets would magically access nested object's property? – Yury Tarabanko Jun 09 '17 at 10:30

1 Answers1

1

This should work.

var my = {
    testFunction: function(text) {
        alert(text);
    }
};

// the string can't be evaluated as nested object hierarchy.
// split it to address the several nodes and properties
var functionName = "my.testFunction".split('.');

var f = window[functionName[0]][functionName[1]];

f('yeha');
Florian Salihovic
  • 3,921
  • 2
  • 19
  • 26