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?