Re: puzzling function constructor
- From: Rod <noblethrasher@xxxxxxxxx>
- Date: Sun, 24 Jun 2007 21:10:17 -0700
On Jun 24, 10:17 pm, RobG <r...@xxxxxxxxxxxx> wrote:
On Jun 25, 12:47 pm, Rod <noblethras...@xxxxxxxxx> wrote:
On Jun 24, 8:34 pm, noddy <n...@xxxxxxxxxxx> wrote:
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.
.
- Follow-Ups:
- Re: puzzling function constructor
- From: noddy
- Re: puzzling function constructor
- References:
- puzzling function constructor
- From: noddy
- Re: puzzling function constructor
- From: Rod
- Re: puzzling function constructor
- From: RobG
- puzzling function constructor
- Prev by Date: Re: puzzling function constructor
- Next by Date: Re: puzzling function constructor
- Previous by thread: Re: puzzling function constructor
- Next by thread: Re: puzzling function constructor
- Index(es):
Relevant Pages
|
|