Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Structure of js code Reply To: Structure of js code

#151636
__
Participant

Brendan’s comment sums up a very good solution.

The problem they’re talking about is global scope: basically, naming conflicts. If you define someVar here, then you have to remember that you can’t use that variable name anywhere else, or you’d have a collision, and the first value would be lost – probably breaking things.

In a more academic perspective, s is logically part of the newsWidget object, and so should be inside that object (rather than outside, in the global scope, where it might get smashed).

By wrapping the whole thing in a self-executing function, you create a closure around s: it’s still available to the newswidget (me in Brendan’s example), but it can’t be reached from the global scope, or anywhere else.