JavaScript call function inside a function by variable name
dynamic, function, javascript, object
Solution
There is no sensible way of accessing an arbitrary variable using a string matching the name of the variable. (For a very poor way to do so, see `eval`).
`[x]();` // DOESN'T WORK
You're trying to call an array as a function
NEITHER `this[x]()`
The function isn't a property of the `inner` object.
`window[x]()`, etc.
Since it isn't a global, it isn't a property of the window object either.
If you need to call a function based on the value of a string variable, then organise your functions in an object and access them from that.
function b() {
alert('got it!');
}
var myFunctions = {
b: b
};
x = 'b';
myFunctions[x]();
Problem
I'm having a difficulty calling a function inside of another function when its name is in a variable: ``` var obj = {} obj.f = function() { var inner = { a: function() { function b() { alert('got it!'); } b(); // WORKS AS EXPECTED x = 'b'; [x](); // DOESN'T WORK, NEITHER this[x]() window[x](), etc. } } inner.a(); } obj.f(); ``` I tried prefixing `[x]()` with different scope paths but so far w/o success. Searching existing answers did not turn up anything. It works with `this[x]()` if `b()` is placed directly inside object inner. I would like to keep `b()` as a function inside `function a()` because of variable scope in `function a()`, otherwise I would need to pass many parameters to `b()`. //// Re duplicate question: Quentin provided a more elegant answer in this thread imo.