What is the difference/advantages of using the $(docu…) with your variables and functions defined inside, from using it with a function and then calling it inside the $(docu…)
$(document).ready(function (){
initialize();
});
function initialize(){
hello
}
over using this:
$(document).ready(function (){
hello
});
These four options all create exactly the same result with declining flexibility:
Example #1
Example #2
Example #3
Example #4
In the first example, you are creating an anonymous function that will be called at document.ready time. That anonymous function calls a separate function
initialize(). Becauseinitialize()is a separate function, it could also be called by other code.In the second example, you just avoid the anonymous function and pass a reference to the
initializefunction directly. This works slightly faster than the first example (one less function call), but is less flexible if you wanted to call more than one function besidesinitialize()from thedocument.ready()handler.In the third example, you just remove the outer
initialize()function and just call the one thing inside it that it was doing from an anonymous function.In the fourth example, the anonymous function is again removed and you just pass a direct reference to the
hellofunction so it will be called directly without any intervening functions.The first option gives you the most flexibility because you can call multiple things inside of
initialize()and you can also callinitialize()from other places in your program. If you don’t need those flexibilities, you can pick any one of the other four options as they all produce the same results, each with a little less flexibility.