I’m trying to build a Javascript library that will provide some functionality for a JQuery Plugin I’m putting together.
I got the following skeleton code from searching online although I’m not quite sure how it all works (I do know it’s a closure). I’ve added my functions via declarations.
(function(window, document, $) {
function func_1(){
return 1;
}
function func_2(){
return 2;
}
})(window, document, jQuery);
So I put the above code in a separate JS file and then source it in my HTML page, then I run try to run the function like so (Note: I have JQuery set up as well):
<script type="text/javascript">
$(document).ready(function() {
console.log(func_1());
});
</script>
However, I seem to be getting some errors in Firebug (ReferenceError: func_1 is not defined).
I have two questions:
- How do I call my functions?!
- I’d like to be able to call the functions in the following format:
className.functionName(). How do I restructure the skeleton code to enable me do this and, say, call my function like this:Device.func_1()?
Thanks for your anticipated assistance.
The closure is used to hide internal functions from the rest of the code. You need to explicitly expose the public functions of the library:
The
(function(window, document, $) {})(window, document, jQuery);part is called an immediately invoked function expression (IIFE). It’s used to avoid leaking all the library functions into the global scope. Otherwise, if some other library had afunc_1function it would either be overwritten or overwrite your library’sfunc_1.The arguments to the function are used to control how the library can affect other parts of the code and relies on it. For example, someone might overwrite the window.$ library so that $ is no longer available everywhere in the code. But since you have a local reference in the closure you can still access it.
Alternatively to using the code above – returning an object – you could also assign your library directly to the global scope: