0

If i have an instance like

var myInstance = new MyInstance();

and put it in a loop. How do i prevent it to make newer instances and point it to the same instance.

Approach i was following was :

if(!score){
  score = new Score();
}

which seems inefficient

Pratish Shrestha
  • 1,712
  • 4
  • 17
  • 26
  • if you never remove score or put it in an array, this call will be called only once (and you have to declare it with `var score = null;`. – Pierre Emmanuel Lallemant Dec 29 '15 at 09:35
  • 1
    If you know you only ever want one instance, why do the initialisation (and therefore have to check the current value) inside the loop at all? Just do it before the loop? – James Thorpe Dec 29 '15 at 09:38
  • Note: `!score` will be true if score have following value: `false`, `0`, `""`, `undefined` or `null` – Rajesh Dec 29 '15 at 09:42
  • Possible duplicate of [Simplest/Cleanest way to implement singleton in JavaScript?](http://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-singleton-in-javascript) – Bek Dec 29 '15 at 09:48
  • My preferred way: `score = score || new Score();` – Shanoor Dec 29 '15 at 10:01
  • @JamesThorpe Inside the loop, there might a condition making `score` null for the next iteration. – Shanoor Dec 29 '15 at 10:07
  • @ShanShan There might be, there might not. There's not enough info to know either way currently. I did preface my comment with "_If_ you know...". – James Thorpe Dec 29 '15 at 10:12

0 Answers0