Dynamically generated function names

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

    Dynamically generated function names

    Hi,
    Does anyone know how to make this work?

    var sectionId = 5;
    repeat_section_ sectionId();

    function repeat_section_ 5(){
    alert("firing") ;
    }

    The function's name contains the variables value, so how do we make
    the engine see that?

    Thanks in advance for any help.
  • Martin Honnen

    #2
    Re: Dynamically generated function names



    Falc2199 wrote:

    [color=blue]
    > Does anyone know how to make this work?
    >
    > var sectionId = 5;
    > repeat_section_ sectionId();
    >
    > function repeat_section_ 5(){
    > alert("firing") ;
    > }
    >
    > The function's name contains the variables value, so how do we make
    > the engine see that?[/color]

    You can use
    window['repeat_section _' + sectionId]();

    --

    Martin Honnen

    Comment

    • Michael Winter

      #3
      Re: Dynamically generated function names

      On 22 Nov 2004 07:33:00 -0800, Falc2199 <JehanNYNJ@aol. com> wrote:

      [snip]
      [color=blue]
      > var sectionId = 5;
      > repeat_section_ sectionId();
      >
      > function repeat_section_ 5(){
      > alert("firing") ;
      > }
      >
      > The function's name contains the variables value, so how do we make the
      > engine see that?[/color]

      Using square bracket notation to construct the name:

      window['repeat_section _' + sectionId]();

      See <URL:http://www.jibbering.c om/faq/faq_notes/square_brackets .html> for
      more information.

      Mike

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

      Comment

      • Duncan Booth

        #4
        Re: Dynamically generated function names

        Falc2199 wrote:
        [color=blue]
        > Hi,
        > Does anyone know how to make this work?
        >
        > var sectionId = 5;
        > repeat_section_ sectionId();[/color]
        Try:
        window['repeat_section _'+sectionId]();[color=blue]
        >
        > function repeat_section_ 5(){
        > alert("firing") ;
        > }
        >[/color]

        A better solution though is to put your functions in an array and then you
        can just subscript the array directly:

        var repeat_section = new Array();
        repeat_section[5] = function() { alert("firing") ; }

        if (repeat_section[sectionId]) {
        repeat_section[sectionId]();
        }

        Comment

        • Randy Webb

          #5
          Re: Dynamically generated function names

          Duncan Booth wrote:[color=blue]
          > Falc2199 wrote:
          >
          >[color=green]
          >>Hi,
          >> Does anyone know how to make this work?
          >>
          >>var sectionId = 5;
          >>repeat_sectio n_sectionId();[/color]
          >
          > Try:
          > window['repeat_section _'+sectionId]();
          >[color=green]
          >>function repeat_section_ 5(){
          >>alert("firing ");
          >>}
          >>[/color]
          >
          >
          > A better solution though is to put your functions in an array and then you
          > can just subscript the array directly:
          >
          > var repeat_section = new Array();
          > repeat_section[5] = function() { alert("firing") ; }
          >
          > if (repeat_section[sectionId]) {
          > repeat_section[sectionId]();
          > }[/color]

          And how is creating an unnecessary array a "better solution" than simply
          accessing the properties/functions of the window object?

          if (window['repeat_section _' + sectionID]())
          {window['repeat_section _'+sectionId]();}

          does the same exact thing yours does without the added overhead of an array.
          --
          Randy
          comp.lang.javas cript FAQ - http://jibbering.com/faq

          Comment

          • Michael Winter

            #6
            Re: Dynamically generated function names

            On Mon, 22 Nov 2004 12:40:50 -0500, Randy Webb <HikksNotAtHome @aol.com>
            wrote:

            [snip]
            [color=blue]
            > if (window['repeat_section _' + sectionID]())
            > {window['repeat_section _'+sectionId]();}
            >
            > does the same exact thing yours does without the added overhead of an
            > array.[/color]

            Well, almost. You called the function, rather than just evaluated the
            reference. :)

            Mike

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

            Comment

            • Duncan Booth

              #7
              Re: Dynamically generated function names

              Randy Webb wrote:
              [color=blue]
              > And how is creating an unnecessary array a "better solution" than
              > simply accessing the properties/functions of the window object?
              >
              > if (window['repeat_section _' + sectionID]())
              > {window['repeat_section _'+sectionId]();}
              >
              > does the same exact thing yours does without the added overhead of an
              > array.[/color]

              Which differs from the first of my two proposed solutions (the one you
              snipped) how exactly? (Apart from mine not having the test, or for that
              matter the typo)

              As to why creating an array is a "better solution", the window object is
              global to the javascript running in that window. If you have a lot of
              javascript then minimising the number of global variables is a good thing
              for the same reason as it is in any other programming language: it
              generally makes your life easier by reducing the time you have to spend
              thinking about possible variable name collisions and reducing the bugs that
              come when you get it wrong.

              It also has other benefits. If you want to find out which 'repeat_section '
              functions exist, it may be simpler to examine an array rather than trying
              to pick them out of all the window properties. Also if you actually want to
              access the functions from several different places you don't have to keep
              retyping that string addition (another possible source of bugs if you
              mistype the string in the wrong place).

              How many reasons did you want? Is someone charging you for the arrays you
              create?

              Comment

              • Randy Webb

                #8
                Re: Dynamically generated function names

                Duncan Booth wrote:
                [color=blue]
                > Randy Webb wrote:
                >
                >[color=green]
                >>And how is creating an unnecessary array a "better solution" than
                >>simply accessing the properties/functions of the window object?
                >>
                >>if (window['repeat_section _' + sectionID]())
                >>{window['repeat_section _'+sectionId]();}
                >>
                >>does the same exact thing yours does without the added overhead of an
                >>array.[/color]
                >
                >
                > Which differs from the first of my two proposed solutions (the one you
                > snipped) how exactly? (Apart from mine not having the test, or for that
                > matter the typo)[/color]

                None, but you offered the array approach as a "better solution". But as
                was pointed out, the if statement in mine should be:

                if (window['repeat_section _' + sectionID])

                And yes, I had a typo.
                [color=blue]
                > As to why creating an array is a "better solution", the window object is
                > global to the javascript running in that window. If you have a lot of
                > javascript then minimising the number of global variables is a good thing
                > for the same reason as it is in any other programming language: it
                > generally makes your life easier by reducing the time you have to spend
                > thinking about possible variable name collisions and reducing the bugs that
                > come when you get it wrong.[/color]

                Unless you use inner functions, functions are global as well. As are
                arrays. But functions are a property of the window object(except inner
                functions).

                With an array:

                Check to see if the array entry exists.
                Call the function.
                That calls the global object and asks for the function.
                The global object checks for the function.
                Then the function is run.

                Without the array, you skip a step of having to look it up in the array.
                You also skip the overhead of the array.
                You also minimize the chance of an error happening when you create the
                array, unless you create it dynamically from all the function names in
                the document.
                [color=blue]
                > It also has other benefits. If you want to find out which 'repeat_section '
                > functions exist, it may be simpler to examine an array rather than trying
                > to pick them out of all the window properties.[/color]

                The window object does it for you. In fact, when you search an array, it
                searches the window properties/objects to find that array and then
                searches it.
                [color=blue]
                > Also if you actually want to access the functions from several different
                > places you don't have to keep retyping that string addition (another possible
                > source of bugs if you mistype the string in the wrong place).[/color]

                I don't see where that has any benefits. There is just as much chance of
                typing a type when typing the array call as there is with a function
                call. Either way, you have to type it out.
                [color=blue]
                > How many reasons did you want?[/color]

                Some that actually made sense to me.
                [color=blue]
                > Is someone charging you for the arrays you create?[/color]

                In overhead and memory, yes.

                --
                Randy
                comp.lang.javas cript FAQ - http://jibbering.com/faq

                Comment

                • Duncan Booth

                  #9
                  Re: Dynamically generated function names

                  Randy Webb wrote:
                  [color=blue]
                  > Duncan Booth wrote:
                  >[color=green]
                  >> As to why creating an array is a "better solution", the window object
                  >> is global to the javascript running in that window. If you have a lot
                  >> of javascript then minimising the number of global variables is a
                  >> good thing for the same reason as it is in any other programming
                  >> language: it generally makes your life easier by reducing the time
                  >> you have to spend thinking about possible variable name collisions
                  >> and reducing the bugs that come when you get it wrong.[/color]
                  >
                  > Unless you use inner functions, functions are global as well. As are
                  > arrays. But functions are a property of the window object(except inner
                  > functions).[/color]

                  I think you have a fundamental misunderstandin g here. A function is global
                  if it is assigned to a global variable (or defined as a named function, but
                  that is just another way to assign it to a global variable). It doesn't
                  matter whether it is an inner function or not, its the variables it is
                  assigned to that matter.
                  [color=blue]
                  >
                  > With an array:
                  >
                  > Check to see if the array entry exists.
                  > Call the function.
                  > That calls the global object and asks for the function.
                  > The global object checks for the function.
                  > Then the function is run.[/color]

                  No, that is plain wrong. Even if the function is defined as global this two
                  step lookup you describe doesn't happen. The sequence is actually:

                  Check to see if the array entry exists.
                  Call the function.
                  Then the function is run.

                  No global object lookups are involved unless the array itself is global.
                  Remember that a function is simply an object, once it has been assigned
                  into the array you can reassign or delete the original global name (if
                  there even was one).
                  [color=blue]
                  > Without the array, you skip a step of having to look it up in the
                  > array. You also skip the overhead of the array.[/color]

                  Without the array the sequence is:

                  Evaluate a string expression
                  Look up the function in the window object
                  Check to see if the function exists
                  Call the function
                  then the function is run

                  Both of these, as originally written involve extra steps, since we both
                  did the lookup of the function twice (once for the check and once for the
                  call), but you can easily store the intermediate value in a variable to
                  avoid that.
                  [color=blue]
                  > You also minimize the chance of an error happening when you create the
                  > array, unless you create it dynamically from all the function names in
                  > the document.[/color]

                  I don't understand this comment. I don't see how creating the array is
                  either more or less error prone than declaring the function normally.

                  function repeat_section_ 5() { ... }

                  versus

                  repeat_section[5] = function() { ... }
                  [color=blue]
                  >[color=green]
                  >> It also has other benefits. If you want to find out which
                  >> 'repeat_section ' functions exist, it may be simpler to examine an
                  >> array rather than trying to pick them out of all the window
                  >> properties.[/color]
                  >
                  > The window object does it for you. In fact, when you search an array,
                  > it searches the window properties/objects to find that array and then
                  > searches it.[/color]

                  If the array is stored in the window object then, yes, accessing the array
                  will involve a lookup on the window object. Once you have the array (one
                  global lookup) you can then pass the collection of functions around as a
                  parameter, or iterate through it calling several of them, or manipulate it
                  in whatever other way seems appropriate without doing any further global
                  lookups. Looking up global variables (i.e. properties of window) in
                  javascript is MUCH slower than accessing local variables.
                  [color=blue]
                  >[color=green]
                  >> Also if you actually want to access the functions from several
                  >> different places you don't have to keep retyping that string addition
                  >> (another possible source of bugs if you mistype the string in the
                  >> wrong place).[/color]
                  >
                  > I don't see where that has any benefits. There is just as much chance
                  > of typing a type when typing the array call as there is with a
                  > function call. Either way, you have to type it out.[/color]

                  I think (although you may disagree) that if you mistype the version based
                  on the string expression all that is likely to happen is that the function
                  never gets called. If you mistype the name of the array variable then you
                  get a javascript error.

                  e.g. compare
                  var method = window['repaet_section _'+sectionId]);
                  with
                  var method = repaet_section[sectionId];

                  The first simply sets method to undefined. The second throws an error.
                  [color=blue]
                  >[color=green]
                  >> How many reasons did you want?[/color]
                  >
                  > Some that actually made sense to me.[/color]

                  I'm sorry if my explanations haven't done that for you.
                  [color=blue]
                  >[color=green]
                  >> Is someone charging you for the arrays you create?[/color]
                  >
                  > In overhead and memory, yes.
                  >[/color]
                  I think that using arrays here is likely to end up with faster code. I do
                  know that I was able to considerably speed up some code I was writing
                  simply by reducing the number of global variable references (e.g. by
                  creating a local variable reference to a global function that was being
                  called many times).

                  As for memory use I would be very, very, very suprised if you could come up
                  with a concrete example where putting functions in an array instead of
                  declaring them separately actually used a measurably greater amount of
                  memory.

                  Also my version saves on all those function names. If you are really worred
                  about memory then 100 functions named 'repeat_section _1' to
                  'repeat_section _100' means you have 100 pointless strings lying around in
                  memory, whereas 100 anonymous functions in an array avoids that.

                  Comment

                  Working...