1

I'm trying to call a method inside another method but I get error "x is not a function". The methods are in very same class. I'm new in node so I don't get its errors at all. My code is :

file 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));

and my b.js file is like:

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

  x(arg){
    // some code
  }
}

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

note: I tried to use "this" before calling x method ( like: this.x(str); ) but "this" is undefined

2 Answers2

3

The much cleaner way to bind would be to do it in the constructor.

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;

Then you should be able to use this just fine.

You can learn more about usage of bind() in JavaScript here (StackOverflow), or here (MDN).

Mat Sz
  • 2,524
  • 1
  • 10
  • 23
1

As you are trying to call a method of the current object and not a global method
You should call it using this so it will be called from the current object
You also will need to bind the method to the created object in the constructor Either manually or you can use auto-bind

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

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

  x(arg) {
    ...
  }
}
h1b9b
  • 1,010
  • 5
  • 16