3

How to call JavaScript or jquery function using variable.

var fnName= "abc"; //how to use fnName as a function call where "abc" will be function name

function abc(){   //definition........ }
2
  • I think these answers might help: stackoverflow.com/questions/359788/… Commented Sep 6, 2017 at 5:53
  • 1
    Best way is to wrap these functions in an object and the object[functionName]() Commented Sep 6, 2017 at 5:56

1 Answer 1

4

Define function globally.

First Way Call as window[functionName]().

function abc() {
  alert('test');
}

var funcName = 'abc';

window[funcName]();

Second Way Add function to defined object.

function parentFunc(name) {
  var childFuncs = {
    "abc": function() {
      alert("test");
    }
  }
  
  childFuncs[name]();
}

var funcName = 'abc';

parentFunc(funcName);

Sign up to request clarification or add additional context in comments.

1 Comment

but it will not work inside any other funcion/nested scope, and may be changing the requirement to declare globally

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.