Problems with OOP

So I have finished JS course provided and I did so a while ago, I have made notes of things that where harder to complete or understand and OOP was one of them. So I looked into other sources and one of them game me an exercise of a stopwatch and I don’t really get how but my variables become undefined, here is a part of my code:

class StopWatch {
    constructor () {
        this.started = 0;
    }
    start() {
        console.log(this.started)
    }
}
const sw = new StopWatch();

startButton.addEventListener('click', sw.start);

the original intention of start() is to change the value of started, how ever the console log displays undefined. And I got another sub question, why does the function run itself if I write into the even listener: sw.start(), without waiting for any clicks???

Add the following to the beginning of the start method:

console.log(this);

Notice that you get the button. So when your start method is executed when you click on the button there is no this.started because this is the button, not the StopWatch class.

One way to solve this is to bind the start method to the class so that this always refers to the class itself when you call the method. Add the following to the constructor:

this.start = this.start.bind(this);

Another way to solve this would be to pass a function to addEventListener that then calls sw.start:

startButton.addEventListener('click', () => sw.start());

This assumes that sw will be in scope.

Because when you write sw.start() you are immediately calling the function and thus it executes. addEventListener takes a function (which it will then call when you click the button), so you want to pass it the name of a function, or you can define the function as I did in my second example above.

Thank you bbsmooth for your replays,
is the solution of binding start method viable if later on I would have to add other methods like stop and reset? I am going to look into this binding thing, because I must have failed the course provided here or this is a bit more advanced.
Anyways you was super helpful

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.