search

Home  >  Q&A  >  body text

es6关于在constructor中new对象为属性的问题,报错

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

import UserService from  './UserService';

 

export default class Controller {

 

  constructor() {

    this.userService = new UserService(); //初始化service

  }

 

  login(req, res, next) {

    var user = {'account''zhangsan''pwd''123'};

    this.userService

      .login(user)

      .then((result)=>{

        // console.log(result);

        res.json(user);

      })

      .catch((error)=>{

        console.log(error);

      });

   

  }

 

}

报错如下

t01982e0291c6a1d93b.jpg

而如果我把new UserService()去掉,改为在login里 new UserService().login(user)就没有问题,但是却似乎违反了面向对象的原则。 我目的是想实现初始化的时候只有一个控制器和一个UserService,而不是每次登陆都要new一个UserService出来。请求高玩指点迷津!

三叔三叔3066 days ago1737

reply all(3)I'll reply

  • 欧阳克

    欧阳克2016-12-05 09:14:58

    1

    2

    3

     constructor() {

           super();

        }


    reply
    0
  • 你的女神

    你的女神2016-12-05 09:14:25

    基本上按你的代码恢复出来的下面的代码没有问题,所以你最好确认一下是哪里的 userService 调用出现了问题。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    class UserService {

        login() {

            return Promise.resolve("login");

        }

    }

     

    class Controller {

     

        constructor() {

            this.userService = new UserService(); //初始化service

        }

     

        login(req, res, next) {

            var user = { "account""zhangsan""pwd""123" };

            this.userService

                .login(user)

                .then((result) => {

                    console.log(result);

                    // res.json(user);

                })

                .catch((error) => {

                    console.log(error);

                });

     

        }

    }

     

    new Controller().login();


    reply
    0
  • 高洛峰

    高洛峰2016-12-05 09:12:55

    可能是this 丢失了,试试

    1

    2

    3

    4

    constructor() {

        this.userService = new UserService();

        this.login = this.login.bind(this);

    }


    reply
    0
  • Cancelreply