如何从变量中调用 javascript 中的方法?

How to call a method in javascript from a variable?

我发现了一些与我的问题相关的问题,但是 none 的答案出于某种原因解决了我的问题。 我想从变量中动态调用 javascript 中的方法。

这是我的代码:

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);
}

这个我也试过了,也没用

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);
}

在上一篇文章中,console.log(fn); 在 DevTools 上写了这个:

ƒ anonymous(
) {
SQL()
}

而我捕获的错误是这样的(SQL是变量的内容):

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)

我的原因是我想这样做是因为我想以不同的方式处理日志和它们的类型。

您可以按照下图进行。

var malt_type;

function json_handler(type){
    malt_type = type;
    try {    
       window[malt_type](); //assuming your SQL() function is defined on the `window` object
    } catch (e) {
       console.log(e);
    }
}

function SQL(){
    console.log(`${malt_type} function ran.`);
}

json_handler("SQL");

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

以上基本上意味着 fn 函数无法访问 SQL 变量。

你可以这样试试:

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);
    }
};