I just started with the second JavaScript course after I finished part 1. I love the video’s and everything is explained very well. It’s a lot of fun.
Could someone help me understand the solution of the section ‘Prototypes’. It’s the exercize where we remodify the Stopwatch(). I found it difficult to understand and it took me some time to make it work only a little bit. I got an error, and after watching the solution I still don’t understand. I copied his code but it doesn’t seem to work eigher:
function Stopwatch(){
let startTime, endTime, running, duration = 0;
Object.defineProperty(this, 'duration', {
get: function(){ return duration},
set: function(value){ duration = value; }
})
Object.defineProperty(this, 'startTime', {
get: function(){ return startTime}
})
Object.defineProperty(this, 'endTime', {
get: function(){ return endTime}
})
Object.defineProperty(this, 'running', {
get: function(){ return running}
})
}
Stopwatch.prototype.start = function(){
if(this.active)
throw new Error('Stopwatch has already started');
this.running = true;
this.startTime = new Date();
}
Stopwatch.prototype.stop = function(){
if(!this.running)
throw new Error('Stopwatch has already been stopped');
this.running = false;
this.endTime = new Date();
const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
this.duration += seconds;
}
Stopwatch.prototype.reset = function(){
this.startTime = null;
this.endTime = null;
this.running = false;
this.duration = 0;
}
const sw = new Stopwatch();
When I type “sw.start()” in the console twice it doesn’t give an error where it suppose to do so, and sw.running is unaffected after (where it suppose to be set to “true”).
Sorry for the long story, here’s my question: What am I doing wrong?