How to change an object attribute inside of a setTimeOut call [duplicate]

I'm creating a "simulation" as a practicing using HTML, CSS and Javascript objects. It's a simulation of testing a smartphone

class smartphone {
  constructor(name, color, weight, screenResolution, camResolution, ram) {
    this.name = name;
    this.color = color;
    this.weight = weight;
    this.screenResolution = screenResolution;
    this.camResolution = camResolution;
    this.ram = ram;
    this.on = false;
  }

And I'm creating a method which "simulates" the startup of a smartphone:

turnOn(){
    if (this.on == false){
      document.getElementById("status").innerHTML = "Turning on...";
      document.getElementById("status").classList.remove("off")
      document.getElementById("status").classList.add("on")
      setTimeout(function(){
        this.on = true; //Line 26
        alert(`${this.name} is on.`) //Line 27
        document.getElementById("img").src = "xperia.png";
        document.getElementById("status").innerHTML = "ON";
    }
      , 3000); // Here I indicate the time (ms) which gonna pass before the code above starts. this is to simulate the time a smartphone takes to turn on 
    }else {
      alert(`${this.name} it's already on.`);
    }
  }

But I got an error when executing line 26 and line 27... First, a console error appears when executing this.on = true; "this.on" it's not defined. And when executing line 27 I got an alert which says undefined is on. I suppose that I get those errors because the function can't access to the object attributes. Is this right? If it is right, what can I do so the function can access to object attributes and redefine them?



from Recent Questions - Stack Overflow https://ift.tt/3bGPYyE
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations