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.

3
  • 1
    maybe this helps Commented May 21, 2016 at 11:03
  • demo why not set the function to a variable ? Commented May 21, 2016 at 11:06
  • try this try this Commented May 21, 2016 at 11:13

1 Answer 1

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]]();

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

1 Comment

Awesome, thank you very much. I add come across this design pattern in my searches but this explanation was very clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.