Express与ES6的类'this'未定义[重复]。

问题描述 投票:0回答:1

你好,我想用express和es6类创建一个应用程序,但每次调用类方法时 this 是未定义的。

UserController.js

export class UserController {

    constructor() {
        console.log('Class Constructed');
        this.service = new UserService();
    }

    create(req, res, next) {
        console.log('console', this);
        this.service.create(req.body).then((user) => {
            res.send(user);
        });
    }
}

路由.js

import { Router } from 'express';
const router = Router();

router.route('/user/create')
    .post(new UserController().create);

我注意到,当我执行 npm run dev我在控制器构造函数中得到了控制台,但是当我从postman中调用'usercreate'时。我得到了 TypeError: Cannot read property 'service' of undefined.

我是不是错过了什么,还是说这种方法是可以的?

如果有人能帮我解决这个问题就太好了。

非常感谢。

javascript node.js express es6-class
1个回答
0
投票

也许你需要 bind create 归类功能

 constructor() {
        console.log('Class Constructed');
        this.service = new UserService();
        this.create = this.create.bind(this);
    }

例子

class UserService {
  create(data) {
    return Promise.resolve({})
  }
}

class UserController {

  constructor() {
    console.log('Class Constructed');
    this.service = new UserService();
    this.create = this.create.bind(this);
  }

  create(req, res, next) {
    console.log('console', this);
    this.service.create(req.body).then((user) => {
      res.send(user);
    });
  }
}

function post(callback) {
  callback({
    body: {}
  }, {
    send: () => {}
  }, () => {})
}

post(new UserController().create);

0
投票

您必须将最近创建的 UserControoller 实例,然后调用其 create 功能,所以 this 是在场景下推断出来的。

router.route(`/user/create`, (req, res, next) => {
    const controller = new UserController();
    controller.create(req, res, next);
});

甚至称之为 create 函数而不存储实例。

router.route(`/user/create`, (req, res, next) => {
    new UserController().create(req, res, next);
});

通过传递 create 函数而不调用自己,该函数将由 express 时而 express 将无法绑定 this 的财产 prototype,因为它没有引用到实例。

希望能帮到你。

© www.soinside.com 2019 - 2024. All rights reserved.