5

Calling a function from a string in JS

 2 years ago
source link: https://www.codesd.com/item/calling-a-function-from-a-string-in-js.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Calling a function from a string in JS

advertisements

I have an array of strings that I wish to use as callbacks, but the below code is not working.

When running the function, I'm getting the error TypeError: fn is not a function logged when callback_array contains only update_front_page_images.

callback_array currently only contains 1 element (update_front_page_images), which is the name of a function I wish to run.

Can someone please let me know what I am doing wrong?

function run_reset_callbacks(callback_array){

    for(var key in callback_array){

        try {
            fn = window[callback_array[key]];
            fn();
        }
        catch(err) {
            console.log('Function \''+callback_array[key]+'\' does not exist. '+err);
        }

    }

}


Make sure you're defining your functions in a way that you can call them as window[] if you want to use this model. You need to define your functions as variables on the window object. A standard function definition will fail.

http://jsfiddle.net/HpXYM/2/

//Works
window.hello = function () {
  alert("hello");
};

//Works
test = function () {
  alert("test");
};

//Fails
function fail() {
  alert("fail")
};

This should solve the problem if you are set on this method but I would recommend you follow Matt Ball's advice.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK