J
J
jallvar2021-03-30 17:13:28
OOP
jallvar, 2021-03-30 17:13:28

How to import a class in javascript?

Hello. I searched on the Internet, but did not understand.
I have the most common class. The object to be created from another file
Class:

class Shop {
    #products = []

    addProducts(products)
    {
        var newProducts = [];

        products.forEach(function (product) {
            newProducts[product["id"]] = new product(
                product["id"],
                product["name"],
                product["description"],
                product["price"]
            );
        });

        this.#products = this.#products.concat(newProducts);

        return this;
    }

    getProduct(id)
    {
        return this.#products[id];
    }
}

module.exports.Shop = Shop;


What I am trying to do:
require("Shop");
var shop = new Shop();

What the interpreter tells me:
Cannot find module 'C:\OpenServer\domains\TestTask\Main.js'

In php, everything seems to be clear, there is include and create a class object. But how to competently do this in js OOP

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-03-30
@bingo347

const {Shop} = require('Shop');
const shop = new Shop();

Well, a couple of notes:
1. You product["id"], product["name"]can write instead product.id, product.name, the fields are known in advance, there is no need to complicate
2. newProducts should be an object {}, not an array [], since the keys are arbitrary id, the #products field also doesn’t really look like an array
3. use let or const instead of var

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question