<variable>=function(){...}

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

    <variable>=function(){...}

    Hi.

    I'm curious about this syntax:
    <variable>=func tion(){...}

    I'm not finding a definition of this syntax, but I see it used at this
    website:


    Here's the usage (in a few different lines) I found there:
    sfHover = function() {
    var sfEls = document.getEle mentById("nav") .getElementsByT agName("LI");
    for (var i=0; i<sfEls.length ; i++) {
    sfEls[i].onmouseover=fu nction() {
    this.className+ =" sfhover";
    }
    sfEls[i].onmouseout=fun ction() {
    this.className= this.className. replace(new RegExp(" sfhover\\b"), "");
    }
    }
    }
    if (window.attachE vent) window.attachEv ent("onload", sfHover);

    Thanks!

    Jim



  • web.dev

    #2
    Re: &lt;variable&gt ;=function(){.. .}


    Jim Moon wrote:[color=blue]
    > Hi.
    >
    > I'm curious about this syntax:
    > <variable>=func tion(){...}
    >
    > I'm not finding a definition of this syntax, but I see it used at this
    > website:
    > http://www.htmldog.com/articles/suckerfish/dropdowns/
    >
    > Here's the usage (in a few different lines) I found there:
    > sfHover = function() {
    > var sfEls = document.getEle mentById("nav") .getElementsByT agName("LI");
    > for (var i=0; i<sfEls.length ; i++) {
    > sfEls[i].onmouseover=fu nction() {
    > this.className+ =" sfhover";
    > }
    > sfEls[i].onmouseout=fun ction() {
    > this.className= this.className. replace(new RegExp(" sfhover\\b"), "");
    > }
    > }
    > }
    > if (window.attachE vent) window.attachEv ent("onload", sfHover);
    >
    > Thanks!
    >
    > Jim[/color]

    The syntax variable = function() {...} simply put is this:

    You are creating a function literal, which is another way to create
    functions. It's similar to the function statement, however in this
    case it is used as an expression rather than a statement and a function
    name is not required.

    The implications of this usage is that you can dynamically create
    functions.

    There is another way of defining functions through the use of the
    Functions(). But it can get awkward pretty quickly.

    Comment

    • sneill@mxlogic.com

      #3
      Re: &lt;variable&gt ;=function(){.. .}

      If you think of everything in JS as an object its easy to see what's
      happening here. Quite simply you're creating a new object of type
      function. The "function() " declares a 'function' object and the curly
      braces defines the function body.

      Hope that helps.

      Steve

      Comment

      • Michael Winter

        #4
        Re: &lt;variable&gt ;=function(){.. .}

        On 13/10/2005 21:17, Jim Moon wrote:
        [color=blue]
        > I'm curious about this syntax:
        > <variable>=func tion(){...}[/color]

        What you have there is a function expression.

        Function declarations:

        function identifier() {
        }

        are parsed into function objects before execution begins[1]. This is why
        one can call a declared function before its definition in the source.

        myFunction(); /* No problem calling this here */

        function myFunction() {
        /* ... */
        }

        Function expressions are different in that they only create function
        objects /if/ they are evaluated. This means that control structures can
        prevent them from being created at all, or repeatedly evaluate the
        expression to create several distinct function objects from the same code.

        var myFunction;

        if(false) {
        myFunction = function() { /* ... */ };
        }

        Here, a function object won't be created because the code branch
        containing the function expression will never be entered.

        This feature affords tremendous flexibility to the author.

        Like function declarations, function expressions can be given identifiers.

        var myVariable = function myFunction() {};

        However, the identifier is only for use within the function itself; it
        allows the function to refer to itself.

        [snip]

        Mike


        [1] To be more precise, function declarations are parsed when
        their containing execution context is entered. That is,
        global function declarations are parsed immediately, but
        inner functions are only parsed when their outer function is
        called. Moreover, they are reparsed on each invocation of
        that outer function.

        function myGlobalFunctio n() {

        function myInnerFunction () {
        /* ... */
        }


        /* ... */
        }

        When interpreted, the function, myGlobalFunctio n, will be
        created immediately. However, the function, myInnerFunction ,
        will not exist yet.

        When the outer function is called, the inner function will
        then be created before statements within myGlobalFunctio n are
        executed. When the scope of myGlobalFunctio n is left, the
        inner function will be destroyed.


        Incidentally, variable declarations work much the same way.
        Declared variables within a particular execution context are
        created before any code is executed. If an initialisation is
        included with the declaration

        var myVariable = ...;

        the variable will exist from the start, but actual
        assignment will not occur until that point in the code is
        reached and evaluated.

        --
        Michael Winter
        Prefix subject with [News] before replying by e-mail.

        Comment

        • Lee

          #5
          Re: &lt;variable&gt ;=function(){.. .}

          Jim Moon said:[color=blue]
          >
          >Hi.
          >
          >I'm curious about this syntax:
          ><variable>=fun ction(){...}[/color]

          I was going to explain that since there is no name between the
          "function" keyword and the parens, that this is creating an
          anonymous function and assigning it to the variable. That led
          me to try the following:

          <html>
          <body>
          <script type="text/javascript">
          var alpha=function beta() { alert("Hello, world!")}
          alpha();
          beta();
          </script>
          </body>
          </html>

          This behaves differently in IE and Firefox. In IE, the function is available by
          either name, but in Firefox, "beta()" is undefined. I can't imagine why this
          would ever matter, but I found it interesting.

          Comment

          • Michael Winter

            #6
            Re: &lt;variable&gt ;=function(){.. .}

            On 13/10/2005 23:05, Lee wrote:

            [snip]
            [color=blue]
            > var alpha=function beta() { alert("Hello, world!")}
            > alpha();
            > beta();[/color]

            [snip]
            [color=blue]
            > This behaves differently in IE and Firefox. In IE, the function is
            > available by either name, but in Firefox, "beta()" is undefined. I
            > can't imagine why this would ever matter, but I found it interesting.[/color]

            That's why I thought to mention it briefly in my post.

            The Identifier in a FunctionExpress ion can be referenced from
            inside the FunctionExpress ion's FunctionBody to allow the
            function to call itself recursively. However, unlike in a
            FunctionDeclara tion, the Identifier in a FunctionExpress ion
            cannot be referenced from and does not affect the scope
            enclosing the FunctionExpress ion.
            -- Section 13, ECMA-262 3rd Ed.

            IE is wrong, as is any other implementation that does the same. They'd
            probably call it a 'feature', though. ;)

            Another interesting test is this:

            if(true) {
            function a() {
            alert('Hello world!');
            }
            }
            a();

            This should fail as the function, a, is a function expression /not/ a
            declaration. This is because function declarations are only permissible
            at global scope, or inside a function body (but still outside block
            statements), so this should be parsed as part of an expression statement.

            Most browsers don't 'pass'.

            Mike

            --
            Michael Winter
            Prefix subject with [News] before replying by e-mail.

            Comment

            • Duncan Booth

              #7
              Re: &lt;variable&gt ;=function(){.. .}

              Michael Winter wrote:
              [color=blue]
              > Another interesting test is this:
              >
              > if(true) {
              > function a() {
              > alert('Hello world!');
              > }
              > }
              > a();
              >
              > This should fail as the function, a, is a function expression /not/ a
              > declaration. This is because function declarations are only permissible
              > at global scope, or inside a function body (but still outside block
              > statements), so this should be parsed as part of an expression statement.[/color]

              I disagree. You should actually get a syntax error for the above code.

              Expression statements are not allowed to begin with either '{' or
              'function', so the 'function' here cannot begin an expression statement and
              there is no other production possible.

              Comment

              • Michael Winter

                #8
                Re: &lt;variable&gt ;=function(){.. .}

                On 14/10/2005 08:50, Duncan Booth wrote:

                [snip]
                [color=blue]
                > Expression statements are not allowed to begin with either '{' or
                > 'function' [...][/color]

                Oops, yes. Good point. I should have looked at the grammar for an
                ExpressionState ment again.

                Still, most browsers do not parse it correctly.

                Mike

                --
                Michael Winter
                Prefix subject with [News] before replying by e-mail.

                Comment

                • Jim Moon

                  #9
                  Re: &lt;variable&gt ;=function(){.. .}

                  Thank you for all the great insight, you guys!

                  Jim


                  Comment

                  Working...