类的编码函数...以及类中的定义...该函数在开始时就被调用...如何防止这种情况并像在函数测试中那样调用它....给出了所描述的错误?
...
// ==========================================================================================
// 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);
}