0

I have 3 files (Wardrobe.js, index.html and script.js). I import Backpack.js on script.js and both as type="module" in my html. When I run my Live Server on VSCode and go to the console no errors show up but when I type the name of my object (smallWardrobe) I get an error that it is not defined. However when I use console.log(smallWardrobe) in my .js it works fine.

Wardrobe.js

class Wardrobe {
    constructor(
        brand,
        numDrawers,
        wWidth,
        wHeight,
        wDepth,
        color,
        material
    ) {
        this.brand = brand;
        this.numDrawers = numDrawers;
        this.size = {
            width: wWidth,
            height: wHeight,
            depth: wDepth,
        };
        this.color = color;
        this.material = material;
    }

    setSize(widthW, heightW, depthW) {
        this.size.height = heightW;
        this.size.width = widthW;
        this.size.depth = depthW;
    }
}

export default Wardrobe;

script.js

import Wardrobe from "./Wardrobe.js";

const smallWardrobe = new Wardrobe(
    "IKEA",
    2,
    10,
    20,
    15,
    "White",
    "Wood"
);

console.log(smallWardrobe);

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Practice: Making classes and objects</title>
    <script type="module" src="Wardrobe.js"></script>
    <script type="module" src="script.js"></script>
  </head>
  <body></body>
</html>

P.S. everything is in the same folder.

  • Variables declared in a module are only in the scope of that module. In general it sounds like your code is *working*, you're just expecting something to be in global scope when manually using the console but that's not the case. But your `console.log` statement in that module demonstrates that you *can* use the variable there. – David Mar 01 '23 at 14:26
  • @David How would I go to be able to access my variables in the browser's console? I was following a LinkedIn tutorial and for the lecturer everything was fine – João Almeida Mar 01 '23 at 14:32
  • You could explicitly assign that variable to the `window` object: `window.smallWardrobe = smallWardrobe;` Though polluting window/global scope kind of goes against what modules intend to accomplish in the first place, but there are valid use cases for it. It's worth looking ahead a bit and defining why you think you *need* to do this. What functionality are you looking to perform which *requires* that this particular variable exist in global scope? – David Mar 01 '23 at 14:36

0 Answers0