0

I am new to JS and learning about creating class and intance. I have a class like this:

class Monitor {
  constructor(
    name,
    color,
    size,
    buttonNumbers,
    producer,
    cableLength,
    cableType,
    powerOn
  )
  {
    this.name=name;
    this.color=color;
    this.size = size;
    this.buttonNumbers=buttonNumbers;
    this.producer=producer;
    this.cable ={
      length:cableLength,
      type: cableType,
    };
    this.powerOn=powerOn;
  }
    turnItOn(powerStatus){
      this.powerOn=powerStatus;
    }
    pressButton(buttonNo){
      this.buttonNumbers=buttonNo;
      console.log('button' + this.buttonNo +' has been pressed');
    }
  
}
export default Monitor;

And I have an instance of this class in another js file like this:

import Monitor from "./Backpack.js";
const halo = 'halo';
console.log(halo);
const computerMonitor = new Monitor(
    'Samsung', 'black', 21, 3, 'Samsung', 22, 'EU', false);
    
const markup = (computerMonitor) => {
  return `
  <div>
    <h3>${computerMonitor.name}</h3>
    <ul>
      <li>Volume: ${computerMonitor.size}</li>
      <li>Color: ${computerMonitor.color}</li>
      <li>Number of pockets: ${computerMonitor.buttonNumbers}</li>
      <li>Cable: Length: ${computerMonitor.cable.length}, Type: ${
    computerMonitor.cable.type} </li>
      <li>Power satus: ${computerMonitor.powerOn ? "On" : "Off"}</li>
    </ul>
  </div>
`;
};
const main = document.createElement("main");
main.innerHTML = markup(computerMonitor);
document.body.appendChild(main);```

I can not call the object "computerMoniter" on the console although the code works well. But I can not call the object: see picture below. For example when I type the object name "computerMoniter" into the console, it returns

"VM1932:1 Uncaught ReferenceError: computerMonitor is not defined at :1:1"

Can not access the class instance from console

My question is that how do I access the instance, in this case computerMonitor, on console? Thank you

Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
  • 1
    It looks like you are using modules, so any variable is module scoped. You'd have to make the variable global: [How to declare global variable in module script](https://stackoverflow.com/q/48612021/218196) – Felix Kling Nov 07 '21 at 19:58

0 Answers0