首页 > 解决方案 > nodejs 超级表达式必须为 null 或函数

问题描述

在我的 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 };

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

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

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

更新:

这确实与我进出口事物的方式有关。

标签: javascriptnode.jsexpressecmascript-6es6-class

解决方案


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

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

推荐阅读