I see examples where JavaScript code including jQuery and jslint use the notation below:
(function(){
// do something
})();
instead of:
// do something
I first thought this is just for local scoping, i.e. creating local variables for the code block without polluting global namespace. But I've seen instances without any local variables at all too.
What am I missing here?
All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private. The parenthesis are only required in this context because function in JavaScript can be both a statement or an expression, depending upon context.
To create a function, you write its return type (often void ), then its name, then its parameters inside () parentheses, and finally, inside { } curly brackets, write the code that should run when you call that function.
A function is defined by using the def keyword, followed by a name of your choosing, followed by a set of parentheses which hold any parameters the function will take (they can be empty), and ending with a colon. In this case, we'll define a function named hello() : hello.py. def hello():
Local Variables Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code.
It's about scope for functions, too - everything declared within the code block is scoped to that anonymous function only. Things are normally made public by the framework
(function($) {
var localVarOnly = "local";
$.fn.myCoolFunction = function() { // in the case of jquery, make this publicly available
otherCoolFunction(); //alerts hi
alert(localVarOnly); // alerts local
};
function otherCoolFunction() { // scoped to this anonymous function only
alert('hi');
};
})(jQuery);
otherCoolFunction(); // undefined
alert(localVarOnly); // undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With