Can someone explain the purpose of this syntax

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • blue

    Can someone explain the purpose of this syntax

    The following is from
    Measure, monetize, advertise and improve your apps with Yahoo tools. Join the 200,000 developers using Yahoo tools to build their app businesses.


    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.Even t.onDOMReady(fu nction() {
    dd = new YAHOO.example.D DOnTop("dd-demo-1");
    dd2 = new YAHOO.example.D DOnTop("dd-demo-2");
    dd3 = new YAHOO.example.D DOnTop("dd-demo-3");
    });

    })();

    </script>
  • Lasse Reichstein Nielsen

    #2
    Re: Can someone explain the purpose of this syntax

    blue <whitelined@gma il.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 - lrn@hotpop.com
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
    'Faith without judgement merely degrades the spirit divine.'

    Comment

    • Jeremy J Starcher

      #3
      Re: Can someone explain the purpose of this syntax

      On Sat, 24 May 2008 23:35:37 +0100, blue wrote:
      The following is from
      Measure, monetize, advertise and improve your apps with Yahoo tools. Join the 200,000 developers using Yahoo tools to build their app businesses.

      >
      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.

      Comment

      • blue

        #4
        Re: Can someone explain the purpose of this syntax

        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.

        Comment

        • blue

          #5
          Re: Can someone explain the purpose of this syntax

          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.

          Comment

          • VK

            #6
            Re: Can someone explain the purpose of this syntax

            On May 25, 2:35 am, blue <whiteli...@gma il.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.Even t.onDOMReady(fu nction() {
            dd = new YAHOO.example.D DOnTop("dd-demo-1");
            dd2 = new YAHOO.example.D DOnTop("dd-demo-2");
            dd3 = new YAHOO.example.D DOnTop("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.

            Comment

            • Richard Cornford

              #7
              Re: Can someone explain the purpose of this syntax

              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.calle ee -) 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.

              Comment

              Working...