我已经声明了一个回调函数,我想调用它....但是失败了....我怎样才能直接调用它?

I have declared a callback function and I want to call it....but failed....how can I call it directly?

class 的编码函数......以及 class 中的定义......该函数在开始时被调用......如何防止这种情况并像在功能测试....给出描述的错误?

...

// ==========================================================================================
// Action class - coded for onMsg to bring it to work....please change if needed
// ==========================================================================================
let action = new class Action {
    constructor() {
        this.msgFunction = (msg) => { msg };
        this.msg = { message: 'Hello!', to_user: 'PeterPan', from_user: 'AlexanderTheGreat' };
        this.onMsg = (MsgFunction) => { MsgFunction(this.msg) };
    }
}

// ==========================================================================================
// action functions: directly called at start - please NOT change
// ==========================================================================================
//let totalTokens = 0;
action.onMsg(function(msg) {
    console.log('==== onMsg ====');
});

// ==========================================================================================
// This is what I want: call the onMsg functions at any time!
// got error:
//      index.js:8 Uncaught TypeError: MsgFunction is not a function
//          at Action.onMsg (index.js:8)
//          at test (index.js:22)
//          at <anonymous>:1:1
// when I write "test()" in the console!
// ==========================================================================================
function test() {
    console.log('==== test ====')
    action.onMsg(action.msgFunction(action.msg));
}

...

在 JavaScript 中,您可以将对函数的引用作为参数传递。在您的代码中,第 8 行(错误所在)表示您传递的参数(test() 的第 2 行)

例如:var myFunc = action.msgFunction 是对函数的引用,以便您稍后调用它。 而 action.msgFunction(action.msg) 是此函数返回的任何内容。

您的代码应如下所示:

function test() {
    console.log('==== test ====')
    action.onMsg(action.msgFunction);
}