0

I'm new to JavaScript, why is this.main undefined on Index.js line 7?

Main.js

class Main {

    constructor(hostname, port) {
        this.hostname = hostname;
        this.port = port;
    }

    init() {
        const express = require("express");
        const app = express();

        console.log("Starting server on port: " + this.port);
        app.listen(this.port);

        const index = require("./index/Index");
        const indexI = new index(this);

        app.get("/", indexI.handle);
    }
}

module.exports = Main;

Index.js

class Index {
    constructor(main) {
        this.main = main;
    }

    handle(req, res) {
        return res.send("MAIN: " + this.main);
    }
}

module.exports = Index;

I need my Index.js to access my Main.js class instance.

EDIT:

I figured out that if I change: app.get("/", indexI.handle); to

app.get("/", (req, res) => {indexI.handle(req, res)});

It works, why is that?

Foreign
  • 385
  • 2
  • 20
  • If you put your code in a snippet, people could try running it and see the error. You can edit your question and use the `<>` button to add a snippet. – Michael Geary Apr 13 '19 at 04:55
  • 1
    For best practices, avoid writing `require` in the methods, you may get unexpected runtime error or other problems since you don't have the dependencies ready on the start of the application. – kit Apr 13 '19 at 04:56

1 Answers1

2

When you pass indexI.handle to app.get, you are simply passing the function, the this in the scope of the function is not the instance of Index.

Try this

app.get("/", indexI.handle.bind(indexI));
kit
  • 535
  • 4
  • 10