+ 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();

7th May 2020, 10:30 PM
Sajid
Sajid - avatar
4 odpowiedzi
+ 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); }
8th May 2020, 12:51 AM
CoffeeByte
CoffeeByte - avatar
+ 2
8th May 2020, 8:41 AM
Sajid
Sajid - avatar
+ 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).
8th May 2020, 2:54 AM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
0
Arb Rahim Badsa I was just experimenting. I knew it wouldnt work
8th May 2020, 8:35 AM
Sajid
Sajid - avatar