Re: puzzling function constructor



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.

.



Relevant Pages

  • Re: puzzling function constructor
    ... It uses the function constructor in a way I have never seen. ... if 'foo' is a function then you can call it with the code ... strings or integers) and don't have to have names. ... into a function expression ...
    (comp.lang.javascript)
  • Re: puzzling function constructor
    ... It uses the function constructor in a way I have never seen. ... if 'foo' is a function then you can call it with the code ... strings or integers) and don't have to have names. ... into a function expression ...
    (comp.lang.javascript)
  • Re: Results of the memswap() smackdown from the thread "Sorting" assignment
    ... Most everything in programming should be done in a disciplined fashion. ... Strings should be what the language standard says they are. ... printf("%d\n", FOO); ...
    (comp.programming)
  • Re: strings question
    ... >> If I am given two strings, named foo and bar, what is the most elegant ... I'm trying to produce a list of DNA sequences for further manipulation ...
    (comp.lang.python)
  • Re: python string comparison oddity
    ... Faheem Mitha wrote: ... this happens because of small objects caching. ... integers or short strings are created, ... Yes, but why is '-' and 'foo' cached, and not '--'? ...
    (comp.lang.python)