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........ }
Omar
  • 32,302
  • 9
  • 69
  • 112
Somnath
  • 368
  • 2
  • 9
  • 22
  • I think these answers might help: https://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string – Schwesi Sep 06 '17 at 05:53
  • 1
    Best way is to wrap these functions in an object and the `object[functionName]()` – Rajesh Sep 06 '17 at 05:56

1 Answers1

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);
Harish Kommuri
  • 2,825
  • 1
  • 22
  • 28