Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    Super Moderator
    Join Date
    Feb 2009
    Location
    England
    Posts
    539
    Thanks
    8
    Thanked 63 Times in 54 Posts

    (function(){})()

    I'm a pretty good Javascript developer, but I'm clearly missing a few tricks. Can someone please explain, in as much technical detail as you like, what the following actually means, or does?

    Code:
    (function(){ someCode(); })();
    or the jQuery use:

    Code:
    (function(window, undefined){ someCode(); })(this);
    lamped.co.uk :: Design, Development & Hosting
    marcgray.co.uk :: Technical blog

  • #2
    Super Moderator
    Join Date
    Feb 2009
    Location
    England
    Posts
    539
    Thanks
    8
    Thanked 63 Times in 54 Posts
    OK, so...

    Code:
    (function(param){alert(param);})('hai');
    ... passes 'hai' as the first parameter to an automatically executed anonymous function. I can see the minification benefits of using this with window, document etc as parameters.

    Why does Javascript execute the function? What syntactic relevance do the parenthesis have?

    Are there any other benefits to this method, other than minification/closure compilation?
    lamped.co.uk :: Design, Development & Hosting
    marcgray.co.uk :: Technical blog

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,189
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    I'm not all that clear that even minification is a big benefit. Closure, okay.

    As for the syntax: It's not all that different than doing
    Code:
        ( new Date( 2010, 10, 8 ) ).getTime();
    Remember that, in JavaScript, functions *ARE* objects.

    So what you are really doing is
    Code:
       ( new Function() )()
    Creating the function as an object and then calling it.

    Why don't you need to use a name for the function, as I did for getTime()? Simply because it is, after all, an *anonymous" function and so neither needs nor can use a name!

    It's weird, I grant you . But it's not the weirdest thing in JavaScript. (See my long argument/discussion with Philip from yesterday and today re Arrays.sort()!! )
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • The Following 2 Users Say Thank You to Old Pedant For This Useful Post:

    jmrker (11-11-2010), Lamped (11-11-2010)

  • #4
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,296
    Thanks
    10
    Thanked 584 Times in 565 Posts
    Quote Originally Posted by Old Pedant View Post

    Why don't you need to use a name for the function, as I did for getTime()? Simply because it is, after all, an *anonymous" function and so neither needs nor can use a name!
    all functions, even the function expressions you call "anonymous", can have names. In the case of function statements, those names are available as local variables. In the case of function expressions, you can optionally assign a variable handle, but the function name (if present) is ALWAYS visible from inside the function.


    you should always give all your functions names, it helps debugging and profiling a lot since firebug reports the names:

    Code:
    (function _hide(a){ return a * b;}())



    EDIT:
    ok, nevermind, i see you were saying it doesn't use a method name. your example was confusing because one is an Object object, whist the other is a function.




    i always write it:
    Code:
    (function(){}())
    which seems to visually suggest that it's an expression.
    Last edited by rnd me; 11-11-2010 at 02:02 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #5
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,037
    Thanks
    0
    Thanked 250 Times in 246 Posts
    One of the benefits of using (function(){})() is you avoid possible variable and function name conflicts. In a company where there are tons of developers working on a single website and sharing common and reusable scripts, it's very helpful to use this technique.

    This technique is also used in Greasemonkey scripts where there's a great risk that userscript variables and functions will conflict with those of the sites the userscript is coded for.

  • #6
    Super Moderator
    Join Date
    Feb 2009
    Location
    England
    Posts
    539
    Thanks
    8
    Thanked 63 Times in 54 Posts
    This has been enormously helpful, thank you.

    I've had a little "shift in perception" and I can see how Javascript would interpret the parenthesis as "get a copy of this object", in this case a function (which of course, is also an object).

    I tend to use the format:

    Code:
    lampedSomething = {
      myVar,
      init: function() {}
    }
    or if I'll be instantiating multiple copies:

    Code:
    function lampedMyFunction() {}
    lampedMyFunction.prototype.doSomething = function() {}
    clientUseOfObject = new lampedMyFunction();
    But at least now I can read the jQuery and similar source properly
    lamped.co.uk :: Design, Development & Hosting
    marcgray.co.uk :: Technical blog


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •