1

I need short messages disappearing after preset time. Please see the fiddle here: http://jsfiddle.net/X88F9/1/.

It works well, what I am not sure about is the reference for each created object:

function addObject() {
    new SomeObj(Math.random() * 1000 + 300);
}

it is not stored in any variable, can I just leave it as it is ? Or do I need to push them in some array ?

I also found this recommendation to put all in closures: https://stackoverflow.com/a/10246262/2969375, but not sure if necessary in my case and if yes, then how.

Community
  • 1
  • 1
John
  • 123
  • 1
  • 10
  • What exactly is your concern? If the objects are not referenced the GC will eventually remove them from memory. – Tasos K. Jan 03 '14 at 14:07
  • if you do not need a reference to the object later on you do not have to store anywhere. Right now it should be deleted by the garbage collector. – philipp Jan 03 '14 at 14:10
  • Not sure I udnerstand. If it's not stored in any variable how do you expect to access it later on? And if you can't access it later on then why do you care about it? – jcoder Jan 03 '14 at 14:10
  • I don't want to access it anymore, just throw a message and disappear after set interval. My concern exactly is if such code will work and the object will exist over the preset interval. – John Jan 03 '14 at 14:43

1 Answers1

1

My answer to the question is: Javascript does not need a reference to the object to work, as proofed by your fiddle. So the question is more about if you need a reference to the object, to do other stuff with it later on. If you, for instance, would like to give the user the ability to click the temporarily display message and stop it from disappearing, than you can put all that code in a closure and do not need a reference, too. But if you would like to display the very same object again after it was removed from the DOM, than you need to store it in an array, other object, or variable, depending on your needs and ways to find it in a list.

philipp
  • 15,947
  • 15
  • 61
  • 106
  • Thank you Philipp, can you clarify the closures or give me some example ? I am not familiar with this. – John Jan 03 '14 at 14:48
  • I found this post: [link](http://stackoverflow.com/a/3564281/2969375) - is that showing the closure? functions defined inside the object constructor ? – John Jan 03 '14 at 14:56