0

I've seen How to execute a JavaScript function when I have its name as a string, Calling a JavaScript function named in a variable, Can I use the value of a variable to initiate a function?, but I can't figure out how to get this working with an array and a for loop.

What I've tried:

I have a few functions, let's say:

function one() { 
    alert('one');
}

function two() {
    alert('two');
}

function three() {
    alert('three');
}

and an array:

callThese = ['one', 'two']

and I want to call one and two.

This doesn't work:

for (i = 0; i < callThese.length; ++i) {
    //console.log(callThese[i]); <--- (outputs one and two)
    window[callThese[i]]();
}

The error I get is TypeError: object is not a function. The functions are definitely there, and they work by calling them manually (ie. one(), two(), etc...).

Sorry if this is a basic mistake, but how do I get this working?? I don't mind a jQuery solution if there is one.

6
  • 5
    newbies seem to do this quite often, use function names stored in strings, and then wanting to call the functions. Don't , there are surely better ways to do this, for instance storing actual references to the functions instead of strings. Commented Jan 10, 2015 at 17:03
  • 1
    If it says object is not a function then window[callThese[i]] is not a function. What is it? Commented Jan 10, 2015 at 17:04
  • 2
    The error suggests the functions aren't globals. If they're defined within another function, they won't be properties of window. Commented Jan 10, 2015 at 17:05
  • @Halcyon callThese[i] should equals one and two Commented Jan 10, 2015 at 17:05
  • 1
    @ṧнʊß yes, but what is window.one, window.two, etc.? Commented Jan 10, 2015 at 17:06

2 Answers 2

4

You need to assign functions to your object. It's not recommended to create global functions (other scripts/frameworks can overwrite them).

var obj = {
        one: function () {
            alert('one');
        },
        two: function () {
            alert('two');
        },
        three: function () {
            alert('three');
        }
    },
    callThese = ['one', 'two'];

for (var i = 0; i < callThese.length; ++i) {
    obj[callThese[i]]();
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can create an object that contains the functions

var myFuncs = {
    one: function () {
        alert('one');
    },
    two: function () {
        alert('two');
    }
}

for (i = 0; i < callThese.length; ++i) {        
    myFuncs[callThese[i]]();
}

Comments

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.