The main advantage of storing your functions in an object is reducing the odds of a name clash. Your first example pollutes the global namespace with scene()
and renderLayer()
which is potentially dangerous if you have a moderate code base that includes other packages and modules.
In the second snippet, scene
is defined inside a anonymous function. This provides two benefits:
- It makes the
scene
object inaccessible to code outside the function. Information hiding is enforced. - The evaluation of the declarations is deferred until the page has completely loaded all content (including images, script files, CSS files, etc.). This guarantees all resources will be available.