I'm new to both JavaScript and YUI. In YUI library examples, you can find many uses of this construct:
(function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, layout = null, ... })();
I think the last couple of parentheses are to execute the function just after the declaration.
... But what about the previous set of parentheses surrounding the function declaration?
I think it is a matter of scope; that's to hide inside variables to outside functions and possibly global objects. Is it? More generally, what are the mechanics of those parentheses?
In JavaScript, the functions wrapped with parenthesis are called “Immediately Invoked Function Expressions" or "Self Executing Functions. The purpose of wrapping is to namespace and control the visibility of member functions. It wraps code inside a function scope and decrease clashing with other libraries.
'the formal variables inside the function parantheses' are also known as parameters . When you say why aren't they declared, you mean why aren't they declared with the keyword var . (Example: var myVariable = 4646; ).
The code is defining an anonymous function (the (function (){ ... }) bit) and then calling it (with no arguments). It then assigns the value to the Browser property of the object that is presumably being defined outside of your code snippet.
In JavaScript, an anonymous function is that type of function that has no name or we can say which is without any name. When we create an anonymous function, it is declared without any identifier. It is the difference between a normal function and an anonymous function.
It is a self-executing anonymous function. The first set of parentheses contain the expressions to be executed, and the second set of parentheses executes those expressions.
It is a useful construct when trying to hide variables from the parent namespace. 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.
See:
http://en.wikipedia.org/wiki/Closure_%28computer_science%29
http://peter.michaux.ca/articles/javascript-namespacing
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