Immediate Functions are the function which gets executed as soon as it's defined. For Example:
(function () { alert('Im an immediate function'); }());
or
(function () {
alert('Im an immediate function');
})();
Only difference between above 2 examples is placement of "()", both are valid but JSLint prefers first one.Observe extra parenthesis after function definition and another set of parenthesis covering whole thing. First set of parenthesis after function definition make sure function executed immediately, and second set of parenthesis is needed only when you are not assigning it to an variable name. if you are assigning it to a variable you can omit them, like
var boo = function () {
return 'Im an immediate function';
}()
Here function gets executed immediately and assigns returning value to a variable "boo". When you have some server side code returning some data which needs to be kept private from further alterations, we can wrap them in immediate function, and expose only needed part of it by providing methods to do so.
No comments:
Post a Comment