473,811 Members | 2,380 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

puzzling function constructor

I have come across this code in a js file.
It uses the function constructor in a way I have never seen.
Can someone explain what is happening here?
Thanks

(function(){
...lines of code...
} ) ();
Jun 25 '07 #1
11 1351
Rod
On Jun 24, 8:34 pm, noddy <n...@toyland.c omwrote:
I have come across this code in a js file.
It uses the function constructor in a way I have never seen.
Can someone explain what is happening here?
Thanks

(function(){
...lines of code...

} ) ();- Hide quoted text -

- Show quoted text -
It is defining an anonymous function then immediately calling it. As
you know, if 'foo' is a function then you can call it with the code
'foo()'. In JavaScript, however, functions are first class (just like
strings or integers) and don't have to have names. So function ()
{...lines of code...} is literally a function just as 2 is literally a
number or 'bar' is literally a string. So you can call function ()
{...lines of code...} just as you would if it were named: by appending
'()' at the end. They could have probably written the code as function
() {...lines of code...}() and gotten the same effect. Also, if the
function takes arguments such as function (x, y, z) {...lines of
code...} then you can call it with code such as (function (x,y,z)
{...})(a,b,c) where a, b, and c are legal JavaScript values.

Jun 25 '07 #2
On Jun 25, 12:47 pm, Rod <noblethras...@ gmail.comwrote:
On Jun 24, 8:34 pm, noddy <n...@toyland.c omwrote:
I have come across this code in a js file.
It uses the function constructor in a way I have never seen.
Can someone explain what is happening here?
Thanks
(function(){
...lines of code...
} ) ();- Hide quoted text -
- Show quoted text -

It is defining an anonymous function then immediately calling it. As
you know, if 'foo' is a function then you can call it with the code
'foo()'. In JavaScript, however, functions are first class (just like
strings or integers) and don't have to have names. So function ()
{...lines of code...} is literally a function just as 2 is literally a
number or 'bar' is literally a string. So you can call function ()
{...lines of code...} just as you would if it were named: by appending
'()' at the end. They could have probably written the code as function
() {...lines of code...}() and gotten the same effect.
No, they couldn't. If a statement starts with the identifier
"function" it will be interpreted as a function *declaration* which
must have a name, otherwise a syntax error will result. You can omit
the name in a function *expression*, hence the use of:

(function(){... })();
If Richard Cornford is still lurking you may have coaxed him out of
retirement.

--
Rob

Jun 25 '07 #3
On Sun, 24 Jun 2007 20:17:08 -0700, RobG <rg***@iinet.ne t.auwrote:
>On Jun 25, 12:47 pm, Rod <noblethras...@ gmail.comwrote:
>On Jun 24, 8:34 pm, noddy <n...@toyland.c omwrote:
I have come across this code in a js file.
It uses the function constructor in a way I have never seen.
Can someone explain what is happening here?
Thanks
(function(){
...lines of code...
} ) ();- Hide quoted text -
- Show quoted text -

It is defining an anonymous function then immediately calling it. As
you know, if 'foo' is a function then you can call it with the code
'foo()'. In JavaScript, however, functions are first class (just like
strings or integers) and don't have to have names. So function ()
{...lines of code...} is literally a function just as 2 is literally a
number or 'bar' is literally a string. So you can call function ()
{...lines of code...} just as you would if it were named: by appending
'()' at the end. They could have probably written the code as function
() {...lines of code...}() and gotten the same effect.

No, they couldn't. If a statement starts with the identifier
"function" it will be interpreted as a function *declaration* which
must have a name, otherwise a syntax error will result. You can omit
the name in a function *expression*, hence the use of:

(function(){... })();
If Richard Cornford is still lurking you may have coaxed him out of
retirement.

I can understand the anonymous function call
function(){...}

what puzzles me is the surrounding brackets and the following ();
can you explain what these achieve please ?
Jun 25 '07 #4
Rod
On Jun 24, 10:17 pm, RobG <r...@iinet.net .auwrote:
On Jun 25, 12:47 pm, Rod <noblethras...@ gmail.comwrote:


On Jun 24, 8:34 pm, noddy <n...@toyland.c omwrote:
I have come across this code in a js file.
It uses the function constructor in a way I have never seen.
Can someone explain what is happening here?
Thanks
(function(){
...lines of code...
} ) ();- Hide quoted text -
- Show quoted text -
It is defining an anonymous function then immediately calling it. As
you know, if 'foo' is a function then you can call it with the code
'foo()'. In JavaScript, however, functions are first class (just like
strings or integers) and don't have to have names. So function ()
{...lines of code...} is literally a function just as 2 is literally a
number or 'bar' is literally a string. So you can call function ()
{...lines of code...} just as you would if it were named: by appending
'()' at the end. They could have probably written the code as function
() {...lines of code...}() and gotten the same effect.

No, they couldn't. If a statement starts with the identifier
"function" it will be interpreted as a function *declaration* which
must have a name, otherwise a syntax error will result. You can omit
the name in a function *expression*, hence the use of:

(function(){... })();

If Richard Cornford is still lurking you may have coaxed him out of
retirement.

--
Rob- Hide quoted text -

- Show quoted text -
You are correct. The only time I ever use "function() {...}()" is when
I'm returning a function from another one, hence "function" in that
case is preceded by the word "return". Guess I just never noticed.

Jun 25 '07 #5
On Sun, 24 Jun 2007 21:10:17 -0700, Rod <no***********@ gmail.com>
wrote:
>On Jun 24, 10:17 pm, RobG <r...@iinet.net .auwrote:
>On Jun 25, 12:47 pm, Rod <noblethras...@ gmail.comwrote:


On Jun 24, 8:34 pm, noddy <n...@toyland.c omwrote:
I have come across this code in a js file.
It uses the function constructor in a way I have never seen.
Can someone explain what is happening here?
Thanks
(function(){
...lines of code...
} ) ();- Hide quoted text -
- Show quoted text -
It is defining an anonymous function then immediately calling it. As
you know, if 'foo' is a function then you can call it with the code
'foo()'. In JavaScript, however, functions are first class (just like
strings or integers) and don't have to have names. So function ()
{...lines of code...} is literally a function just as 2 is literally a
number or 'bar' is literally a string. So you can call function ()
{...lines of code...} just as you would if it were named: by appending
'()' at the end. They could have probably written the code as function
() {...lines of code...}() and gotten the same effect.

No, they couldn't. If a statement starts with the identifier
"function" it will be interpreted as a function *declaration* which
must have a name, otherwise a syntax error will result. You can omit
the name in a function *expression*, hence the use of:

(function(){... })();

If Richard Cornford is still lurking you may have coaxed him out of
retirement.

--
Rob- Hide quoted text -

- Show quoted text -

You are correct. The only time I ever use "function() {...}()" is when
I'm returning a function from another one, hence "function" in that
case is preceded by the word "return". Guess I just never noticed.
So what you are saying is that

(function(){... })();
turns the anonymous function declaration function(){...} ;
into a function expression
right ?
Jun 25 '07 #6
Rod
On Jun 24, 11:18 pm, noddy <n...@toyland.c omwrote:
On Sun, 24 Jun 2007 21:10:17 -0700, Rod <noblethras...@ gmail.com>
wrote:


On Jun 24, 10:17 pm, RobG <r...@iinet.net .auwrote:
On Jun 25, 12:47 pm, Rod <noblethras...@ gmail.comwrote:
On Jun 24, 8:34 pm, noddy <n...@toyland.c omwrote:
I have come across this code in a js file.
It uses the function constructor in a way I have never seen.
Can someone explain what is happening here?
Thanks
(function(){
...lines of code...
} ) ();- Hide quoted text -
- Show quoted text -
It is defining an anonymous function then immediately calling it. As
you know, if 'foo' is a function then you can call it with the code
'foo()'. In JavaScript, however, functions are first class (just like
strings or integers) and don't have to have names. So function ()
{...lines of code...} is literally a function just as 2 is literally a
number or 'bar' is literally a string. So you can call function ()
{...lines of code...} just as you would if it were named: by appending
'()' at the end. They could have probably written the code as function
() {...lines of code...}() and gotten the same effect.
No, they couldn't. If a statement starts with the identifier
"function" it will be interpreted as a function *declaration* which
must have a name, otherwise a syntax error will result. You can omit
the name in a function *expression*, hence the use of:
(function(){... })();
If Richard Cornford is still lurking you may have coaxed him out of
retirement.
--
Rob- Hide quoted text -
- Show quoted text -
You are correct. The only time I ever use "function() {...}()" is when
I'm returning a function from another one, hence "function" in that
case is preceded by the word "return". Guess I just never noticed.

So what you are saying is that

(function(){... })();
turns the anonymous function declaration function(){...} ;
into a function expression
right ?- Hide quoted text -

- Show quoted text -
right.

Jun 25 '07 #7
On Jun 25, 2:18 pm, noddy <n...@toyland.c omwrote:
On Jun 24, 10:17 pm, RobG <r...@iinet.net .auwrote:
[...]
No, they couldn't. If a statement starts with the identifier
"function" it will be interpreted as a function *declaration* which
must have a name, otherwise a syntax error will result. You can omit
the name in a function *expression*, hence the use of:
(function(){... })();
[...]
>
So what you are saying is that

(function(){... })();
turns the anonymous function declaration function(){...} ;
into a function expression
right ?
No. A function declaration can't be anonymous. A function
declaration *must* have a name, and therefore isn't anonymous. A
function expression doesn't need a name - you can provide one but it's
pretty useless (except in IE which, from memory, makes it a global
variable but I may be wrong there).

Maybe examples are better:

<script>
function fnName (){...}

// and

function fnName1(){
function fn2name(){...}
}

</script>

and so on are function declarations, they must have a name, whereas:

<script>

var x = function() {...}

// and

(function(){... })

// and

var x = {}
x.foo = function(){...}

// and

var y = {
bar: function(){...}
}

</script>

and so forth are function expressions.
--
Rob

Jun 25 '07 #8
On Mon, 25 Jun 2007 16:18:21 +1200, noddy <no***@toyland. comwrote:

OK I'm pretty sure I've got it now

Thank you both for your patience and help

N
Jun 25 '07 #9
RobG wrote:
On Jun 25, 2:18 pm, noddy <n...@toyland.c omwrote:
>>On Jun 24, 10:17 pm, RobG <r...@iinet.net .auwrote:
[...]
>>>No, they couldn't. If a statement starts with the identifier
"function" it will be interpreted as a function *declaration* which
must have a name, otherwise a syntax error will result. You can omit
the name in a function *expression*, hence the use of:
(function(){... })();
[...]
>So what you are saying is that

(function(){... })();
turns the anonymous function declaration function(){...} ;
into a function expression
right ?

No. A function declaration can't be anonymous. A function
declaration *must* have a name, and therefore isn't anonymous. A
function expression doesn't need a name - you can provide one but it's
pretty useless (except in IE which, from memory, makes it a global
variable but I may be wrong there).

Maybe examples are better:

<script>
function fnName (){...}

// and

function fnName1(){
function fn2name(){...}
}

</script>

and so on are function declarations, they must have a name, whereas:

<script>

var x = function() {...}

// and

(function(){... })
Can this function expression function as-is?

In other words, without appending the call operator or assigning it a
reference, how would one use it?
// and

var x = {}
x.foo = function(){...}

// and

var y = {
bar: function(){...}
}

</script>

and so forth are function expressions.
--
-Lost
Remove the extra words to reply by e-mail. Don't e-mail me. I am
kidding. No I am not.
Jun 27 '07 #10

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

Similar topics

2
2114
by: penny336 | last post by:
dear all, i wrote a class integerSet which contain element as integer here is the driver program main IntegerSet a( n ); a.inputSet(); IntegerSet b (a); IntegerSet c(2*n); c = a.unionOfIntegerSets( b ); the problem is in union operation, how to avoid calling copy constructor at
12
3297
by: Olumide | last post by:
I'm studying Nigel Chapman's Late Night Guide to C++ which I think is an absolutely fantastic book; however on page 175 (topic: operator overlaoding), there the following code snippet: inline MFVec operator+(const MFVec& z1, const MFVec& z2) // Global function { MFVec res = z1; res += z2 return res; // WHY???
5
2876
by: bipod.rafique | last post by:
Hello All, I am little confused about the constructor function. Say I have a class like the following class test{ int a; public: test(){}
6
1703
by: Alexis Nikichine | last post by:
Hello, Today, I have a function: function f() { } and am looking for a way of distinguishing, from inside f, whether it
41
2594
by: Telmo Costa | last post by:
Hi. I have the following code: -------------------------------------- function Tunnel() { //arguments(???); } function Sum() { var sum = 0; for (i=0; i<arguments.length; i++) sum += arguments;
26
2154
by: Patient Guy | last post by:
The code below shows the familiar way of restricting a function to be a method of a constructed object: function aConstructor(arg) { if (typeof(arg) == "undefined") return (null); this.property1 = arg; this.property2 = aConstantDefinedGlobally; this.method1 = function (anArg) {
28
4345
by: Larax | last post by:
Best explanation of my question will be an example, look below at this simple function: function SetEventHandler(element) { // some operations on element element.onclick = function(event) {
14
1565
by: Nickolay Ponomarev | last post by:
Hi, Why does http://www.jibbering.com/faq/ uses new Function constructor instead of function expressions (function(...) { ... }) when defining new functions? E.g. for LTrim and toFixed. Is the reason that you want to avoid accidental closures? Or does some obscure browser does not support function expressions? This just looks weird, given that http://www.jibbering.com/faq/#FAQ4_40 says to only use eval() (which is not really much...
9
23777
by: Morten Lemvigh | last post by:
Is it possible to pass a pointer to a constructor or a class definition as argument to a function? Maybe in a way similar to passing function pointers...? The function should construct a number of objects using the given constructor. The objects should all inherit from a base class. It's not possible to pass actual objects, since it's not given on beforehand, how many should be created.
0
9607
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10652
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10395
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10408
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10137
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9211
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7673
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6895
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3874
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.