gpt4 book ai didi

javascript - 无法从类的方法调用构造函数中声明的属性

转载 作者:搜寻专家 更新时间:2023-10-30 21:55:54 25 4
gpt4 key购买 nike

我有一个 HomeController,它有方法索引。我已经在构造函数中声明了 this.data 变量。当我在 index 方法中调用 this.data 时,出现错误消息,如

类型错误:无法读取未定义的属性“数据”

这个 HomeController:

import Controller from "./../../vendor/controller";
import * as express from "express";
import hException from "./../helper/exception.helper";

class HomeController extends Controller {
data:object
constructor(){
super()
this.data = {
tes: 'tes'
}
}
async index(request:express.Request, response:express.Response, next:express.NextFunction):Promise<any>{
try {
let template = 'home/index';
//next to viewer
response.render(template, { layout: 'dashboard', data: this.data});
} catch (error) {
next(new hException(error))
}
}
}

export default HomeController

路由调用HomeController:

import * as express from "express";
import Controller from "./../../controller/home.controller";

import { Jwt as MJwt } from "./../../middleware/auth.middleware";

class Routes {
private router:express.Router = express.Router()
private path:string = '/'
private controller:Controller
private MJwt = new MJwt()
constructor() {
this.controller = new Controller;
this.run()
}

public run(){
this.router.route(this.path)
.get(
this.controller.index
);
}
}

export default Routes

最佳答案

通过使用箭头函数 声明HomeController 的方法解决了这个问题link了解详情。或使用绑定(bind)函数 link了解详情。

Solved with arrow function

关于javascript - 无法从类的方法调用构造函数中声明的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56538232/

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