I am new to javascript and was trying to create a stopwatch object as described in a youtube video. Following is the code:
function Stopwatch(){
let durationVal = 0;
let startFlag = 0;
this.start = function(){
if (startFlag === 0){
durationVal = Date.now()
startFlag = 1;
}
else{
throw new Error('Stopwatch is already running')
}
}
this.stop = function(){
if(startFlag === 1){
durationVal = Date.now() - durationVal
startFlag = 0;
}
else{
throw new Error('Stopwatch is not running')
}
}
this.duration = durationVal;
this.reset = function(){
durationVal = 0;
}
}
When I try to create an object and access its duration property
let sw = new Stopwatch()
sw.start()
sw.stop()
console.log(sw.duration)
It returns a zero. However, when I change my javascript to use a method to get the duration value:
this.duration = function(){
return durationVal;
}
it gives the correct value. Can you explain why?