0

I need to be able to call functions in jquery based on a variable - like windowvarname in javascript. This is not a duplicate question because the other answer is for javascript and not jquery.

For example;

var name = 'test1';

function test1() {
    alert('test1 called');
}

function test2() {
 alert('test2 called');
}

name();

I want to do this so that I can dynamically call functions based on the results from an array.

I've been searching high and slow but I can seem to be able work this out.

Danbuntu
  • 165
  • 1
  • 9

1 Answers1

1

A better approach will be to create a Module and store all your functions there with variable names as properties of that module.

var name = 'test1';

var func = {
    test1: function() {
        alert('test1 called');
    },
    test2: function() {
        alert('test2 called');
    },
    test3: function() {
        alert('test3 called');
    },
    test4: function() {
        alert('test4 called');
    },
    test5: function() {
        alert('test5 called');
    }
}

var array = ['test1', 'test2', 'test3', 'test4', 'test5'];

func[name]();
func[array[3]]();
func[array[array.length - 1]]();
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
  • Awesome, thank you very much. I add come across this design pattern in my searches but this explanation was very clear. – Danbuntu May 21 '16 at 15:31