javascript - 在 NodeJS 方法中使用类函数作为参数

标签 javascript node.js

我正在尝试使用一个类函数作为另一个方法中的参数。但是我在尝试这样做时一直在获取未定义的功能。下面是我的类(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/

相关文章:

node.js - 意外的 token 导入

javascript - jQuery : Copy masked password value correctly

javascript - 屏幕不滚动 Expo web

javascript - 检测 odoo 界面何时完全加载

node.js - Mongoose 中 document.save() 后的人口数量错误

node.js - tslint 错误 - 阴影名称 : 'err'

javascript promise 处理,无法处理错误

javascript - 当 `` `type ="module"``` 或 import 时函数不工作

node.js - 如何将 BLOB 格式的图像上传到 Firebase 存储?

node.js - 如何将数据作为整数而不是 NodeJS 中的字符串存储到 MongoDB 中?