Remember the below , this is the simple and best example for IIFE (Immediately Invoked Function Expressions).
An another way for IIFE
It will be invoked automatically without being called. You must add parentheses(based on above two - I prefer second one ) in starting of the function and end of the function to express that it is a function expression.
(function () { // body of the function }());
An another way for IIFE
(function () { // body })();
It will be invoked automatically without being called. You must add parentheses(based on above two - I prefer second one ) in starting of the function and end of the function to express that it is a function expression.
How it is work ?
At the end we have added (), this is the reason its calling automatically. So remember adding () this at end is must. So that IIFE will work for you.
Why do we want to use this?
Most of the time for the below two reasons, we are using IIFE.
1. For Better namespace management
2. Closures
Next chapter we can see a good example about closures with IIFE.
No comments:
Post a Comment