I’ve seen JavaScript files formatted two different ways and I have no idea what the differences are.
<script>
function foo () { /* a function */ }
</script>
name = {
foo: function () { /* a function */ }
foo2: function () { /* a different function */ }
}
What is the difference between these two ways of writing JavaScript, and why would I do one verese the other.
The second method creates the functions as members of the object
name. This has the effect of encapsulating them insidename, rather than creating them inside the global namespace. JavaScript can be very problematic in terms of variable and function naming, due to the way it utilizes the global namespace. For example, forgetting to use thevarkeyword when declaring a variable inside a function will cause the variable to have global scope instead of function scope.So, that second method allows you to create just one variable at the global level, and use it as a container for several more variables and functions without worry of colliding with other global function & variable names.
A common pattern you’ll see (and recommended in Douglas Crockford’s Javascript: The Good Parts):
In effect, the only global variable I have created here is
myApplication, and that is unlikely to cause a name collision with anything else in the global namespace. I can call my functions like: