类内部的函数未定义

时间:2019-10-21 20:07:44

标签: javascript node.js

我有一个表示数据库中项目的类。

class Item{

   constructor(serialNumber) {
        this.serialNumber = serialNumber;
    }

    /**
     * Queries database, gets the item and all of it's information
     * @returns query result
     */
    async getItem() {

        //Query database 
        var [rows, fields] = await db.execute('query...', [this.serialNumber]);


        //we have no results, bad entry or is a sales order
        if (rows.length < 1) {
            return rows;
        }

        //checking item
        var check = await _checkIbutton(); //is undefined

        ...

    }

    /**
    * Checks if the item is also an iButton
    * @returns query results if they exist
    */
    async _checkIbutton() {


        var [rows, fields] = await db.execute('Query...', [this.serialNumber]);

        if (rows.length < 1) {
            return { status: false };
        }
        return { status: true, data: rows };
    }

}

函数checkIbutton()检查项目是否为特定类型的项目。当我在getItem()中调用该函数时,出现错误:ReferenceError: _checkIbutton is not defined.

_checkIbutton在类的范围内,getItem也是如此。为什么会出现此错误?

1 个答案:

答案 0 :(得分:2)

class Test {

  constructor() {
      this.func1();
  }

  async func1() {

      console.log("asc");
      await this.func2();
  }

  async func2() {
      console.log("22asc");
  }
}
const test = new Test();

您必须使用此关键字。“ this”是指调用者对象(父对象)