The three functions are a wrapper, preloader, and image changer.
The wrapper is this part:
(function () {
...
}());
You’ll note that his code ends with })(); while mine ends with }());
They both achieve the same objective of invoking the function, but his ends up invoking the enclosing parenthesis, while mine behaves more like how we normally invoke functions.
The difference can be seen more clearly with the following example:
var wrapper = function () {
...
};
(wrapper());
(wrapper)();
It makes more consistent sense for the invoking parenthesis to be on the function, rather than outside it, and I agree with Douglas Crockford that the second version looks like dogballs hanging off the end.
Anyhow that’s my little rant about the wrapper.
The purpose of the wrapper is a good coding practice to protect your code from undesired changes from outside of your code, and to protect the browser from functions and variables within your own code.
The preload function ensures that the images have all been loaded, so that there’s no delay while the image is being loaded (as it’s already been preloaded) when the next image is used.
The last function occurs on the click event, which increases a counter and changes the image to the next image.
ok, just a little confusion still (sorry)
The preload function
function preload(){
for(c=0;c<arguments.length;c++) {
preloads[preloads.length]=new Image();
preloads[preloads.length-1].src=arguments[c];
}
c=0;
}
loops through the preloads and loads the images.,
what does preloads[preloads.length-1].src=arguments[c]; do?
in the last function, this.src points the image with the id(‘dynamic-image’)
The last function happens every time the event happens right?
Can you explain why the first function wraps everything and what is the difference between having the parenthesis outside the function?
The wrapper around everything means that the code can’t accidentally interact with other scripts in the same page because the variables are local to the function they are defined in.
Both ways with the parentheses work but one has the ones to execute the function attached to the function normally while the other applies it outside of the parentheses that wrap the function itself (which is done so that the anonymous function doesn’t have the keyword ‘function’ at the start of the statement where it has a different meaning).
(x()) as compared to (x)() - where x is the function - the first more accurately reflects the relationship between x and ()