+ 1
How do I access "a" here in the stop method?
function StopWatch() { this.duration = 0; this.reset = () => { this.duration = 0 } this.start = () => { var a = setInterval(()=>this.duration++,1000) } this.stop = () => { console.log(this.start.a) } } var sw = new StopWatch();
4 Réponses
+ 6
Yoy can't because you declarate "a" as a var in "start" scope, to solve this you can declarate "this.a=null" after "this.duration" than write in your "start" method:
this.a=setInterval(()=>this.duration++,1000);
and "stop" method:
this.stop=()=>{
clearInterval(this.a);
}
+ 2
luis calderón thanks
+ 1
Here is a small piece of explanation :
You've written :
console.log(this.start.a);
I hope you already know, what does the '.' (dot) do here. The dot is used to access any property or method from an object, right? So to make 'this.start.a' accessible, you should either return the 'a' as an object from 'this.start' (but then you have to write 'this.start().a') or you must make it a property of the main class. (StopWatch in this case).
0
Arb Rahim Badsa I was just experimenting. I knew it wouldnt work