在方法NodeJS中将类函数用作参数

时间:2019-06-04 21:02:37

标签: javascript node.js

我试图在其他方法中将类函数用作参数。但是我一直试图获得未定义的功能。下面是我的班级样子:

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())

我不确定该怎么做。任何帮助表示赞赏。 谢谢

2 个答案:

答案 0 :(得分:2)

您需要传递函数名称(作为字符串)。当前您正在调用 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')

答案 1 :(得分:1)

(不是答案,只是一个解释。)

没有顶级functionA,在functionA内部定义了Test。这是一个实例方法,因此它甚至在Test的命名空间中也不可见(Test.functionA未定义)。

无论如何,您都需要传递functionA(对函数的引用),而不是functionA()(对调用函数产生的结果的引用)。

最干净的方法确实是@cale_b建议的。