首页 > 解决方案 > My class created doesn't export an object

问题描述

I need to create the class ShoppingCart in the file ShoppingCart.js and export it to a test file and i get the error that my class is not a constructor

I know the problem is not in import export because before creating the js file i got the error that it couldn't find the module. I also tried creating a new instance of the class inside the file and it worked

file ShoppingCart.js
class ShoppingCart{
    constructor(name){
        this.name=name
    }
}

module.exports = { ShoppingCart}

The code for my test file is

 const ShoppingCart = require("./ShoppingCart")
 new ShoppingCart()

when i run the test file i get

TypeError: ShoppingCart is not a constructor

标签: javascriptclassobject

解决方案


您当前正在导出具有以下属性的对象ShoppingCart

module.exports = { ShoppingCart }
//               ^^   object   ^^

只需导出ShoppingCart

module.exports = ShoppingCart;

或者,在导入时,引用ShoppingCart对象的属性:

const { ShoppingCart } = require("./ShoppingCart")

推荐阅读