The past few sites I worked on and primarily event driven using jquery and i usually make my functions as so
function abc() {
//do stuff
}
abc();
and
function foo() {
var a = $('.aaa');
var b = $('.bbb');
var c = $('.ccc');
function animal() {
//do stuff
}
animal();
function pet() {
//do stuff
}
pet();
}
foo();
I know its not the best practice but, im still learning and it seems to work. I just would like to know the way I should handle this for now on.
Actually the code in your example (the first one) is not the best thing you can do if you’re defining all these functions in the global scope (like properties/methods of the global object window). I prefer using module pattern http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript
I recommend you to read the whole book in the upper link. Another thing which is extremely useful – Stoyan Stefanov’s JS Patterns book http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752.
Another alternative of your example (the second one) is self-executing function:
Self-executing functions are helping you to do some initialization work when loading the page for first time. You can attach events or/and do another stuff which you should do once. It’s preventing you from polluting the global scope and doing init multiple times.