473,241 Members | 1,465 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,241 software developers and data experts.

Can someone explain the purpose of this syntax

The following is from
http://developer.yahoo.com/yui/examp.../dd-ontop.html

What does the (function(){ })(); syntax actually do? I'm going to guess
that is creates an unnamed function?! Many thanks.

<script type="text/javascript">

(function() {

var dd, dd2, dd3;
YAHOO.util.Event.onDOMReady(function() {
dd = new YAHOO.example.DDOnTop("dd-demo-1");
dd2 = new YAHOO.example.DDOnTop("dd-demo-2");
dd3 = new YAHOO.example.DDOnTop("dd-demo-3");
});

})();

</script>
Jun 27 '08 #1
6 1320
blue <wh********@gmail.comwrites:
What does the (function(){ })(); syntax actually do? I'm going to
guess that is creates an unnamed function?! Many thanks.
It creates an unnamed function, and it immediately calls that
function. The effect is to create a new scope for the code in the
body of the function. Local variables declared inside the function
will not be visible afterwards.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jun 27 '08 #2
On Sat, 24 May 2008 23:35:37 +0100, blue wrote:
The following is from
http://developer.yahoo.com/yui/examp.../dd-ontop.html

What does the (function(){ })(); syntax actually do? I'm going to guess
that is creates an unnamed function?! Many thanks.
[code snipped]

Exactly, though the phrase you are looking for is "anonymous functions".

If a function will only be called one place, then anonymous functions
allow cleaner code because the "sub-function" is right there, where used.
You'll also want to read up on "javascript closures", a related and very
useful coding technique.
Jun 27 '08 #3
Lasse Reichstein Nielsen wrote:
It creates an unnamed function, and it immediately calls that
function. The effect is to create a new scope for the code in the
body of the function. Local variables declared inside the function
will not be visible afterwards.
Cheers for that. I see now the (function(){}) bit declares the function,
and the () bit executes it. Would it's use be to just keep the global
namespace clean/seperate? Cheers.
Jun 27 '08 #4
Jeremy J Starcher wrote:
Exactly, though the phrase you are looking for is "anonymous functions".
I knew it had a name.
If a function will only be called one place, then anonymous functions
allow cleaner code because the "sub-function" is right there, where used.
Thanks for explaining that.
You'll also want to read up on "javascript closures", a related and very
useful coding technique.
Just did a search for that, and some interesting results - which I'll
read in the morning, bit late to understand. Thank you for pointing that
out, it'll prove useful.
Jun 27 '08 #5
VK
On May 25, 2:35 am, blue <whiteli...@gmail.comwrote:
The following is fromhttp://developer.yahoo.com/yui/examples/dragdrop/dd-ontop.html

What does the (function(){ })(); syntax actually do? I'm going to guess
that is creates an unnamed function?! Many thanks.

<script type="text/javascript">

(function() {

var dd, dd2, dd3;
YAHOO.util.Event.onDOMReady(function() {
dd = new YAHOO.example.DDOnTop("dd-demo-1");
dd2 = new YAHOO.example.DDOnTop("dd-demo-2");
dd3 = new YAHOO.example.DDOnTop("dd-demo-3");
});

})();

</script>
A couple of years ago I was myself highly puzzled by this construct.
It is an age old task to define a function and to execute it
immediately. At older times - and this is what I used to - it was
simply
function myFunction() {
// statements
}
myFunction();
There are two drawbacks as I see it:
1st and the main one, I guess :-) - it is not cool
2nd is that myFunction unconditionally goes to the global space so
overrides any other myFunction defined before that. While the "rude
namespace" is not so important for a stay alone program, for a
libraries friendly program one may want to have "shy namespace" so no
global var will be created unless the needed identifier is not in
use; otherwise it warns or uses reserve identifiers.
In the latter case wrapped anonymous function may be of a good help:
(function() {
if (typeof myFunction == 'undefined') {
myFunction = functionBody;
}
else {
// namespace conflict handling
}
})();

It is important that the function has to be anonymous then because of
different treatment of function declaration wrapped into expression.
Having
(function f() {
// function body
})();
JavaScript doesn't create global function f but JScript does so global
f remains in the memory. One of rare situations when JavaScript vs.
JScript difference is important to know.
Jun 27 '08 #6
blue wrote:
Lasse Reichstein Nielsen wrote:
>It creates an unnamed function, and it immediately calls that
function. The effect is to create a new scope for the code
in the body of the function. Local variables declared inside
the function will not be visible afterwards.

Cheers for that. I see now the (function(){}) bit declares
the function, and the () bit executes it. Would it's use be
to just keep the global namespace clean/seperate? Cheers.
That is certainly one use. Most applications of the construct originate
from attempts to introduce nation of 'private' into a language where (on
the face of it) everything seems to be public. That is, they were used
for encapsulation. Overlapping that, the construct is also used grouping
related functionality into discrete components/modules (particularly
where internal details don't need to be (or rather 'should not be')
exposed outside of the module/component.

However, javascript is a functional programming language and directly
calling function expressions long pre-dates most of its current
applications. For example, I recall an example where the idea was to
start off a recursive examination of a tree structure were the function
resulting form the expression would call itself if it needed to (using -
arguments.calleee -) and the initial inline call to the anonymous
function expression was used to start the process off and pass in the
starting tree node as an argument.

Richard.

Jun 27 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: bo | last post by:
And why and where one should use one vs. the other? Verbally, it seems like semantics to me--but obviously there is some actual difference that makes references different and or preferable over...
21
by: Gactimus | last post by:
Can anyone explain what the lines with the '*' by them do? ----------- #ifndef _COUNTER_H #define _COUNTER_H #include <iostream> using namespace std; class Counter
2
by: Erik | last post by:
Hi Everyone, I'm having real problems compiling some source for eVC4++. The errors I am getting are below: It all seems to be centred around winsock. If I move the afsock.h reference to before...
12
by: Andrew Ducker | last post by:
And no, this isn't a complaint about break - I'm very happy to make things explicit. However, why isn't the format something like: switch(myVariable) { case 1: { //Do Something
5
by: Miles Keaton | last post by:
I'm switching to PostgreSQL from MySQL. Using the SAMs book called PostgreSQL which has been great to skim the surface of the differerences. I had never even heard of things like triggers,...
7
by: CMirandaman | last post by:
I have another newbie question I could use some help with. I ran across this code in one of the MS training guides: public class NullTokenVisitor {...} public class Application { public...
6
by: amerar | last post by:
Hi All, I'm not good at Javascript, so I am trying to understand this small bit of code: var groups=document.$fm.category.options.length; var group=new Array(groups); for (i=0; i<groups;...
4
by: schal | last post by:
hi Experts, what is the purpose writing a date in the following format: where x.event_date >= {ts '1980-01-01 00:00:00'} versus like this: where x.event_date >= '1980-01-01 00:00:00' what...
1
by: okonita | last post by:
I need major help resolving a UDF error. My environment id DB2 UDBv8.2 and v9.1 on a Linux and Windows server. I am getting a SQL20148N error which states as follows: SQL20148N Routine...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.