gpt4 book ai didi

javascript - 为什么使用类时我的 var 未定义?

转载 作者:行者123 更新时间:2023-12-01 01:05:47 24 4
gpt4 key购买 nike

我是 JavaScript 新手,为什么是 this.main Index.js 第 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;

索引.js

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

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

module.exports = Index;

我需要 Index.js 来访问 Main.js 类实例。

编辑:

我发现如果我改变: app.get("/", indexI.handle);

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

它有效,这是为什么?

最佳答案

当您将 indexI.handle 传递给 app.get 时,您只是传递函数,即函数作用域中的 this不是 Index 的实例。

试试这个

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

关于javascript - 为什么使用类时我的 var 未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55662117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com