473,396 Members | 1,815 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,396 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 1327
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.