在 node.js 中不断出现 "x is not a function" 错误

Constantly getting "x is not a function" error in node.js

我试图在另一个方法中调用一个方法,但出现错误 "x is not a function"。 这些方法非常相同 class。 我是节点的新手,所以我根本没有得到它的错误。我的代码是:

文件 app.js :

const express = require("express");
const app = express();
const pkg = require("./app/b.js");

const port = 3001;

pkg("Hi");

app.listen(port, () => console.log("app is running on port " + port));

我的 b.js 文件是这样的:

class BFile{
  y(str){
    // some irrelative codes
    x(str)
  }

  x(arg){
    // some code
  }
}

const obj = new BFile()
module.exports = obj.y

注意:我尝试在调用 x 方法之前使用 "this"(例如:this.x(str);)但是 "this" 未定义

因为您正在尝试调用当前对象的方法而不是全局方法
您应该使用 this 调用它,以便从当前对象调用它
您还需要将该方法绑定到构造函数中创建的对象 手动或您可以使用 auto-bind

class BFile{
  constructor () {
    this.x = this.x.bind(this);
    // Or autobind(this);
  }

  y(str) {
    ...
    this.x(str);
    ...
  }

  x(arg) {
    ...
  }
}

更简洁的绑定方法是在构造函数中进行绑定。

class BFile {
  constructor() {
    this.y = this.y.bind(this);
    this.x = this.x.bind(this);
  }

  y(str) {
    this.x(str); // this is needed here.
  }

  x(arg) {
    // some code
  }
}

const obj = new BFile();
module.exports = obj.y;

那你应该可以使用this就好了。

您可以在 JavaScript here (Whosebug), or here (MDN) 中了解有关 bind() 用法的更多信息。