Search code examples
javascriptnode.jsmethod-call

How to call a method in javascript from a variable?


I found some questions related to my question, but none of the answers solved my problem for some reason. I want to call a method in javascript dynamically from a variable.

This is my code:

var malt_type;

export function json_handler(type){
    malt_type = type;

    try {
        window[malt_type]();
    } catch (e) {
        console.log(e);
    }
}

function SQL(){
    console.log(malt_type);
}

I tried this also, but didn't work either

var malt_type;

export function json_handler(type){
    malt_type = type;
    try {    
        var fnName = malt_type + "()";
        var fn = new Function(malt_type);
        console.log(fn);
        fn();
    } catch (e) {
        console.log(e);
    }
}

function SQL(){
    console.log(malt_type);
}

In the previous one the console.log(fn); writes this on the DevTools:

ƒ anonymous(
) {
SQL()
}

And the error I catch is like this (SQL is the content of the variable):

ReferenceError: SQL is not defined
    at eval (eval at json_handler (json_handler.js:11), <anonymous>:3:1)
    at Module.json_handler (json_handler.js:13)
    at Show (server.js:39)
    at Socket.<anonymous> (server.js:20)
    at Socket.emit (events.js:314)
    at TCP.<anonymous> (net.js:672)

My reason is that I want to do this is because I want to handle logs and the type of them differently.


Solution

  • Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was created.

    https://developer.mozilla.org/.../Function

    The above basicaly means the fn function doesn't have access to SQL variable.

    You could try it like this:

    var malt_type;
    
    export function json_handler(type){
        malt_type = type;
    
        // if it exists execute it
        functions[type] && functions[type]();
    }
    
    const functions = {
        SQL: function SQL(){
            console.log(malt_type);
        }
    };