【问题标题】:nodejs Super expression must either be null or a functionnodejs 超级表达式必须为 null 或函数
【发布时间】:2021-04-22 19:44:00
【问题描述】:

在我的 UserService 类中,我试图用 super 调用我的基类构造函数。如果我尝试这样做,我会收到以下错误:TypeError: Super expression must either be null or a function

这是我的 UserService 类

import { Service } from './Service';

class UserService extends Service {
  constructor(model) {
    //Calls Service contructor with specified model.
    super(model);
  }
}

export default { UserService };

这是基类:

import autoBind from 'auto-bind';

class Service {
  constructor(model) {
    this.model = model;
    autoBind(this);
  }
}

export default { Service };

看了一圈,有人说可能跟类名拼写不正确有关。我检查了我的,但它们都是正确的。

其他人说这可能是这些类的导出和导入方式。

我对不同的导出语法不是很熟悉,所以这可能是问题所在?

更新:

这确实与我导入和导出东西的方式有关。

【问题讨论】:

    标签: javascript node.js express ecmascript-6 es6-class


    【解决方案1】:

    无法重现您的问题。您可能没有正确导入服务。这是一个工作示例:

    Service.js:

    import autoBind from 'auto-bind';
    
    class Service {
      model;
      constructor(model) {
        this.model = model;
        autoBind(this);
      }
    }
    
    export { Service };
    

    UserService.js:

    import { Service } from './Service';
    
    class UserService extends Service {
      constructor(model) {
        super(model);
      }
    }
    
    export { UserService };
    

    main.js:

    import { UserService } from './UserService';
    
    const model = { name: 'teresa teng' };
    
    const userService = new UserService(model);
    console.log(userService.model.name);
    

    输出:

    teresa teng
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-23
      • 2023-01-29
      • 1970-01-01
      • 2021-10-20
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多