Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Jamie Moore
Jamie Moore
3,943 Points

OOJS help - struggling with the concept

Hey!

I've been following along with the OOJS course and i'm getting a bit confused, so I tried to build something that I thought would help demystify things a little, but i'm running into a few issues.

I'm trying to make a simple stopwatch application, but only the workings, i'm not concerned with showing anything to the user at this point.

In my app.js file, I have a few variables declared to allow a few buttons to be pressed:

const start = document.querySelector(`#start`);
const stop = document.querySelector(`#stop`);
const reset = document.querySelector(`#reset`);
const stopwatch = new Stopwatch;

start.addEventListener('click', stopwatch.start);
stop.addEventListener('click', stopwatch.stop);
reset.addEventListener('click', stopwatch.reset);

And in my Stopwatch.js file, I have a class defined with some methods.

class Stopwatch {
    constructor() {
        this.reading = 0;
        this.isActive = false;
        this.startTime = null;
        this.stopTime = null;
        this.duration = null;
    };

    start() {
        console.log('starting');
        this.startTime = new Date();
    };

    stop() {
        console.log('stopping');
        this.stopTime = new Date();
        this.duration = `${(this.stopTime - this.startTime) / 1000}s`;
    };

    reset() {
        this.isActive = false;
        this.startTime = null;
        this.stopTime = null;
        this.duration = null;
    };
}

My question is... when I try and use the methods (stopwatch.start(), stopwatch.stop() etc), the objects values aren't being updated. If I replaced the this keyword with stopwatch, then it does work, but doesn't this make using OOJS redundant?

Any help would be appreciated.

Thanks.

1 Answer

Sascha Bratton
Sascha Bratton
3,665 Points

This looks to me like it would work. Why do you think your object properties are not being updated?