首页 > 解决方案 > 如何从类中的另一个函数调用函数

问题描述

我有以下问题:我想printHello从函数调用函数testHello。该printHello函数独立工作,但是,当我尝试printHello从该testHello函数调用时,我得到一个引用错误。谢谢您的帮助。


class Test {
  constructor(name) {
    this.name;
  }

  printHello(parameter) {
    console.log(parameter);
  }

  testHello() {
    printHello(printHello(this.name));
  }

}
var test = new Test("Sandro");
test.printHello("hello"); //works, prints "Hello" to the Console 
test.testHello(); // does not work: Reference Error: printHello is not defined

标签: javascriptfunctionreferenceerror

解决方案


使用this关键字。另外,你有一些错误(我评论了他们)

class Test{
    constructor(name){
        this.name = name; // <- you need to assign the `name` to `this.name`
    }

    printHello(parameter){
        console.log(parameter);
    }

    testHello(){
        this.printHello(this.name); // <- you had double invocation here
    }

}
var test = new Test("Sandro");
test.printHello("hello");   //works, prints "Hello" to the Console 
test.testHello();  // does not work: Reference Error: printHello is not defined


推荐阅读