Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJamie Moore
3,997 PointsOOJS 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
3,671 PointsThis looks to me like it would work. Why do you think your object properties are not being updated?