我正在尝试使用一个类函数作为另一个方法中的参数。但是我在尝试这样做时一直在获取未定义的功能。下面是我的类(class)的样子:
class Test{
constructor(name){
this.name = name;
}
functionA(){
console.log('My name is John');
}
functionB(){
console.log('My name is Steve');
}
}
function caller(args){
let test = new Test('t1');
return test.args;
}
caller(functionA())
我不知道该做什么。任何帮助表示赞赏。 谢谢
最佳答案
您需要传递函数名称(作为字符串)。当前您正在调用 functionA()
,它不是已定义的函数。
查看下面修改后的代码:
class Test {
constructor(name) {
this.name = name;
}
functionA() {
console.log('My name is John');
}
functionB() {
console.log('My name is Steve');
}
}
function caller(args) {
let test = new Test('t1');
// use bracket notation to CALL the function, and include the () to call
return test[args]();
}
// pass the function name as a string
caller('functionA')
关于javascript - 在 NodeJS 方法中使用类函数作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56451331/