1

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>
1
  • 3
    You've not defined a Foo. The foo you did define is not referenceable through the global namespace so you can't use it externally (you would need to set up some reference first). undefined is non-configurable, non-writable in the global namespace, creating it as a property like this makes it writable so can be considered bad practice. Commented Dec 9, 2015 at 20:01

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.