Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do parentheses surrounding an object/function/class declaration mean? [duplicate]

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?

like image 333
user54692 Avatar asked Jan 13 '09 20:01

user54692


People also ask

What do parentheses mean in JavaScript?

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.

What do you call the variables inside the parenthesis of a function?

'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; ).

What do empty parentheses mean in JavaScript?

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.

What is a anonymous function in JavaScript?

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.


1 Answers

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

like image 126
Andy Hume Avatar answered Sep 30 '22 23:09

Andy Hume