simple question

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

    #1

    simple question

    could somebody tell me the difference between those two styles:

    function abc(var1, var2){ /* logic in here */ }

    and

    abc = function(var1, var2){ /* logic in here */ };

    When / why would I use one over the other?

    Thanks,

    Alex

  • Evertjan.

    #2
    Re: simple question

    Alex wrote on 14 mrt 2005 in comp.lang.javas cript:
    [color=blue]
    > could somebody tell me the difference between those two styles:
    >
    > function abc(var1, var2){ /* logic in here */ }
    >
    > and
    >
    > abc = function(var1, var2){ /* logic in here */ };[/color]

    different styles.

    [color=blue]
    > When / why would I use one over the other?[/color]

    Because proramming is such an individual art.


    --
    Evertjan.
    The Netherlands.
    (Replace all crosses with dots in my emailaddress)

    Comment

    • Alex

      #3
      Re: simple question

      so, there's no functional difference between the two?

      Comment

      • Dietmar Meier

        #4
        Re: simple question

        Alex wrote:
        [color=blue]
        > could somebody tell me the difference between those two styles:
        >
        > function abc(var1, var2){ /* logic in here */ }
        >
        > and
        >
        > abc = function(var1, var2){ /* logic in here */ };[/color]

        The differences between these two statements are explained in detail
        in chapter 13 of ECMA-262.

        The only difference I see that affects your code's behaviour is that
        if you use the function declaration (the first of your two variants),
        "abc" becomes a property of the current variable object, which is not
        the global object if your function declaration is nested inside
        another function body.

        So

        function foo() {
        function bar() {
        ...
        }
        }

        is not the same as

        function foo() {
        bar = function() {
        ...
        }
        }

        but rather the same as

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

        This could be a pitfall in some situations.

        Another important point is that function expressions (like the second
        of your two variants) were implemented in JavaScript 1.2 (IIRC), so
        old scripting engines would show an error if you use them.

        ciao, dhgm

        Comment

        • Florian Loitsch

          #5
          Re: simple question

          Florian Loitsch wrote:

          and to answer your initial question:
          try to use the "function abc(...){...}" form. Some compilers/interpreters
          might optimize this line more easily (although I doubt it. but it can't be
          worse that the other construct).
          // florian loitsch

          Comment

          • Florian Loitsch

            #6
            Re: simple question

            Alex wrote:
            [color=blue]
            > so, there's no functional difference between the two?[/color]
            there is one:
            take the following example:
            function f() {
              var g;
              g(); // works!!
              function g() {
                alert("in g");
              }
            }
            function h() {
              var g;
              g(); // doesn't work.
              g = function() {
                alert("in g");
              };
            }

            In other words: function-declarations (without the '=') take precedence over
            undefined vars.
            In most cases the difference is neglectable though, as you shouldn't mix
            function-declarations and vars.
            // florian loitsch

            Comment

            • Alex

              #7
              Re: simple question

              Thanks for the info! I guess I could have looked in the ECMA-262
              myself... <blush>

              AW

              Comment

              • Michael Winter

                #8
                Re: simple question

                Alex wrote:
                [color=blue]
                > could somebody tell me the difference between those two styles:
                >
                > function abc(var1, var2){ /* logic in here */ }
                >
                > and
                >
                > abc = function(var1, var2){ /* logic in here */ };[/color]

                The first is a function declaration and the second is a function
                expression. They are not simply styles, but completely different
                constructs with differing semantics.

                First of all, they are usable in different locations. A function
                declaration may not appear inside blocks, with the exception of other
                functions. That is,

                function identifier() {
                function anotherIdentifi er() {
                }
                }

                is fine, but

                function identifier() {
                if(condition) {
                function anotherIdentifi er() {
                }
                }
                }

                is not. Function expressions, on the other hand, can be placed where
                any expression is permitted.

                The behaviour of the two also differs. A function declaration acts
                like a variable declaration, in that it is parsed as soon as execution
                enters the relevant scope[1].

                function myFunction() {
                var result = innerFunction() ;

                function innerFunction() {
                }
                }

                However, the function object defined by a function expression is only
                created when the expression has been evaluated. This allows the
                creation of conditional functions. Something that you'll see in the
                FAQ notes is code along the lines of:

                var getElementById;

                if(!document.ge tElementById) {
                getElementById = function(i) {
                /* Use document.all to obtain a reference to i. */
                };
                } else {
                getElementById = function(i) {
                return document.getEle mentById(i);
                };
                }

                Only one of those function expressions will be evaluated, so only one
                function object will be created. Moreover, the function will not be
                available until after the if..else statement has completed. Attempting
                to use it prior will result in an error, unlike with function
                declarations.
                [color=blue]
                > When / why would I use one over the other?[/color]

                There are various uses for function expressions. I've already provided
                one. Another is the creation of an anonymous function object. This can
                be useful in a couple of cases.

                1) Creating a one-time unique scope:

                (function() {
                /* ... */
                )();

                Notice the position of the brackets, and the presence of the call.

                2) Creating static/prototype methods:

                MyObject.protot ype.method = function() {
                /* ... */
                };

                As there will generably be no need to expose the function outside
                the context of the MyObject object, why name it so that access is
                possible?

                Be aware that an identifier can be used with function expressions,
                however this identifier is only available within the function body and
                is useful for recursion or if the function has some other reason to
                reference itself.

                MyObject.protot ype.method = function myMethod() {
                /* Use myMethod to reference this function object. */
                };

                /* The identifier, myMethod, should NOT be available here. */

                Hope that helps,
                Mike


                [1] There is a specific order with regard to variable, function, and
                argument instantiation within function contexts. Section 10.1.3 -
                Variable Instantiation describes this, but essentially the order
                is variable, argument, function with declarations of a latter
                type overwriting the value of a former. For example,

                function identifier(vari able) {
                function variable() {}

                var variable;

                /* The identifier, variable, is a function. */
                }

                However, if an assignment to a local variable (which is entirely
                different to a simple declaration) occurs, the value will be
                replaced:

                function identifier() {
                var variable = 'value';

                function variable() {}

                /* The identifier, variable, is a string. */
                }

                This occurs because instantiation is completely finalised before
                code execution begins so an assignment, no matter how early, will
                take precedence.

                --
                Michael Winter
                Replace ".invalid" with ".uk" to reply by e-mail.

                Comment

                • Michael Winter

                  #9
                  Re: simple question

                  Dietmar Meier wrote:

                  [snip]
                  [color=blue]
                  > Another important point [early parsers][/color]

                  I would think that the earliest parser that will be encountered is
                  JavaScript 1.3 and its equivalents, which is used by most versions of
                  NN4 and does (IIRC) handle function expressions. I don't believe
                  anything earlier is worth considering under normal circumstances.

                  Mike

                  --
                  Michael Winter
                  Replace ".invalid" with ".uk" to reply by e-mail.

                  Comment

                  • Alex

                    #10
                    Re: simple question

                    fantastic!! that really helps a lot! thank you so much!

                    AW

                    Comment

                    • Michael Winter

                      #11
                      [Minor corrections and clarifications] Re: simple question

                      Michael Winter wrote:

                      [snip]
                      [color=blue]
                      > function identifier() {
                      > if(condition) {
                      > function anotherIdentifi er() {
                      > }
                      > }
                      > }
                      >
                      > is not.[/color]

                      You could argue that the function inside the if block is an
                      expression, just as

                      l_value = r_value;

                      is an expression. Indeed, this latter example is an
                      ExpressionState ment in the grammar. However, the ExpressionState ment
                      rule forbids the starting tokens '{' (opening brace) and 'function',
                      meaning that arbitrary blocks and function expressions cannot occur in
                      this manner. However, the one-time scope example (below) shows a way
                      in which function expressions can be evaluated immediately.

                      [snip]
                      [color=blue]
                      > var getElementById;
                      >
                      > if(!document.ge tElementById) {
                      > getElementById = function(i) {
                      > /* Use document.all to obtain a reference to i. */
                      > };
                      > } else {
                      > getElementById = function(i) {
                      > return document.getEle mentById(i);
                      > };
                      > }[/color]

                      There should be at least three branches in this code. The first should
                      be executed if the document.getEle mentById method is available, the
                      second if the document.all collection is available, and the final
                      block for the case where no equivalent substitute can be provided:

                      var getElementById;

                      if(document.get ElementById) {
                      getElementById = function(i) {
                      return document.getEle mentById(i);
                      };
                      } else if(document.all ) {
                      /* ... */
                      } else {
                      getElementById = function() {return null;};
                      }

                      [snip]
                      [color=blue]
                      > 1) Creating a one-time unique scope:
                      >
                      > (function() {
                      > /* ... */
                      > )();[/color]

                      The third line is missing a closing brace:

                      })();

                      [snip to footnote]
                      [color=blue]
                      > However, if an assignment to a local variable (which is entirely
                      > different to a simple declaration) occurs, the value will be
                      > replaced:
                      >
                      > function identifier() {
                      > var variable = 'value';
                      >
                      > function variable() {}
                      >
                      > /* The identifier, variable, is a string. */
                      > }
                      >
                      > This occurs because instantiation is completely finalised before
                      > code execution begins so an assignment, no matter how early[/color]

                      ....in the source, ...
                      [color=blue]
                      > will take precedence[/color]

                      ....because it will be executed after instantiation.

                      Mike

                      --
                      Michael Winter
                      Replace ".invalid" with ".uk" to reply by e-mail.

                      Comment

                      • Hal Rosser

                        #12
                        Re: simple question


                        "Alex" <alexwagner@wal la.com> wrote in message
                        news:1110822040 .266843.211760@ o13g2000cwo.goo glegroups.com.. .[color=blue]
                        > so, there's no functional difference between the two?
                        >[/color]

                        If a function returns a value, you can use it *as if* it was the value.
                        for instance: if functionX(argX) returns a number, then you can use it like
                        this:

                        var x = functionX (argX) * anotherVar


                        Comment

                        • Michael Winter

                          #13
                          Re: [Minor corrections and clarifications] Re: simple question

                          Michael Winter wrote:
                          [color=blue]
                          > However, the ExpressionState ment rule forbids the starting tokens
                          > '{' (opening brace) and 'function', meaning that arbitrary blocks
                          > and function expressions cannot occur in this manner.[/color]

                          On second thoughts, the opening brace doesn't refer to blocks as
                          blocks are statements, not expressions. Presumably, it refers to
                          object literals, but I don't see why objects would be forbidden but
                          not array literals.

                          Mike

                          --
                          Michael Winter
                          Replace ".invalid" with ".uk" to reply by e-mail.

                          Comment

                          • Florian Loitsch

                            #14
                            Re: [Minor corrections and clarifications] Re: simple question

                            Michael Winter wrote:
                            [snip][color=blue]
                            > On second thoughts, the opening brace doesn't refer to blocks as
                            > blocks are statements, not expressions. Presumably, it refers to
                            > object literals, but I don't see why objects would be forbidden but
                            > not array literals.[/color]
                            because they cause confusion with empty blocks:
                            is "{};" an empty block followed by a semicolon, or the creation of an empty
                            object? Agreed: it doesn't make any difference for the semantique of the
                            program, but it does for LALR-parsers.
                            A slightly more difficult example for parsers:
                            {}.x = 3;
                            if the parser already shifted to block, the .x is invalid.
                            // florian

                            Comment

                            • Dietmar Meier

                              #15
                              Re: simple question

                              Michael Winter wrote:
                              [color=blue]
                              > I would think that the earliest parser that will be encountered is
                              > JavaScript 1.3 and its equivalents, [...]. I don't believe
                              > anything earlier is worth considering under normal circumstances.[/color]

                              It makes a difference if there's just a feature missing or if the
                              script produces an error when the document loads. At least I must
                              be aware of such problems and be able to tell my client that the
                              document might throw an error if one of his visitors thinks that
                              NN3 or an old web TV fits for browsing the web today.

                              ciao, dhgm

                              Comment

                              Working...