I am reading and trying some examples of self executing JavaScript function. I found a few examples on how to call them, but I am still a little confused as to the proper way to create and call them. For example, If I have a foo method inside this self executing function that takes 2 parameters, param1 and param2. How do I call this method? You can pass global objects such as window, document, etc. What about parameters that are not global but need in order for the function to perform some action?
Here is an example:
foo.js
(function (window, document, $, undefined) {
function foo(param1, param2) {
//do stuffs here
}
})(window, document, jQuery);
index.html:
<script src="~/Scripts/Custom/foo.js"></script>
<script type="text/javascript">
var myFoo = new Foo("parameter1","parameter2");
</script>
Not having functions inside global scope is whole point of having IIFE as called by Ben Alman. Point of them is invoke some code without affecting global scope. You can create as many counters as you want and they will not affect each other as they are in separate "scope".
If insist to use Foo in global scope with using IIFE, you want to update your example and need to assign it to window parameter you passed it inside IIFE.
(function (window, document, $, undefined) {
window.Foo = foo;
function foo(param1, param2) {
//do stuffs here
}
})(window, document, jQuery);
This way you will have Foo in global scope and thus you can use new Foo(param, param)