How to execute a function whose name is in the database?

1

I would like to know how to execute a JavaScript function by taking its name from the database. Example:

data["nome_coluna"] // essa será a informação que estará no banco. (exemplo: somar();)

// Aí o objetivo é executar essa função dentro de um if.

if(data["nome_coluna"] != ""){
    data["nome_coluna"];
}

Is there a way to do this? Is this form wrong? If so, how?

NOTE: The purpose of this is to make when I buy a card and it has a function that should happen immediately, so call the function that is saved in the database. As there are many cards, it is not feasible to be doing an if for each card, since they are different functions.

    
asked by anonymous 12.11.2018 / 20:22

2 answers

1

You can check if the function exists before attempting to execute it. But for this the function must have global scope to call it with the object window :

if(window[data["nome_coluna"]]){
    window[data["nome_coluna"]]();
}

In this case the function name must come without the () in the variable data["nome_coluna"] . The window object has the functions created on the page with global scope as properties (you can have a scope scope in this documentation ).

    
12.11.2018 / 20:56
0

In order to do this you can create a class and use it as follows;

If it's in your file or properly imported , you can call minhaClasse.['nome_coluna']() or this.['nome_coluna']() , depending on the context.

Using your example and considering that it is coming from the bank without () :

data["nome_coluna"] 

if(data["nome_coluna"] != ""){
    minhaClasse.[data["nome_coluna"]](); // Ou como eu disse
    // minhaClasse.[this.data["nome_coluna"]](); // Não sei o seu contexto
}

I think that's how it goes.

It has the way that Sam said above also, to use without class, window[data["nome_coluna"]] , if with () , and window[data["nome_coluna"]]() , if strong> ()

    
12.11.2018 / 20:34