473,249 Members | 1,686 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,249 software developers and data experts.

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.
Jul 23 '05 #1
8 4794


Falc2199 wrote:

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?


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

--

Martin Honnen
http://JavaScript.FAQTs.com/
Jul 23 '05 #2
On 22 Nov 2004 07:33:00 -0800, Falc2199 <Je*******@aol.com> wrote:

[snip]
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?


Using square bracket notation to construct the name:

window['repeat_section_' + sectionId]();

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

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #3
Falc2199 wrote:
Hi,
Does anyone know how to make this work?

var sectionId = 5;
repeat_section_sectionId(); Try:
window['repeat_section_'+sectionId]();
function repeat_section_5(){
alert("firing");
}


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]();
}
Jul 23 '05 #4
Duncan Booth wrote:
Falc2199 wrote:

Hi,
Does anyone know how to make this work?

var sectionId = 5;
repeat_section_sectionId();


Try:
window['repeat_section_'+sectionId]();
function repeat_section_5(){
alert("firing");
}

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]();
}


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.javascript FAQ - http://jibbering.com/faq
Jul 23 '05 #5
On Mon, 22 Nov 2004 12:40:50 -0500, Randy Webb <Hi************@aol.com>
wrote:

[snip]
if (window['repeat_section_' + sectionID]())
{window['repeat_section_'+sectionId]();}

does the same exact thing yours does without the added overhead of an
array.


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

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #6
Randy Webb wrote:
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.


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?
Jul 23 '05 #7
Duncan Booth wrote:
Randy Webb wrote:

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.

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)


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.
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.
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.
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.
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.
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).
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.
How many reasons did you want?
Some that actually made sense to me.
Is someone charging you for the arrays you create?


In overhead and memory, yes.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq
Jul 23 '05 #8
Randy Webb wrote:
Duncan Booth wrote:
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.
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).


I think you have a fundamental misunderstanding 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.

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.
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).
Without the array, you skip a step of having to look it up in the
array. You also skip the overhead of the array.
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.
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.
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() { ... }
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.
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.


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


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.
How many reasons did you want?
Some that actually made sense to me.


I'm sorry if my explanations haven't done that for you.
Is someone charging you for the arrays you create?


In overhead and memory, yes.

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.
Jul 23 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Richard A. DeVenezia | last post by:
At line this.timerId = setInterval (function(){this.step()}, 100) I get error dialog Error:Object doesn't support this property or method. If I change it to this.timerId = setInterval...
3
by: KathyB | last post by:
Hi, I'm trying to find a way to validate input text boxes where I don't know the names until the page is rendered. I've got 2 validate functions that fire with the onsubmit button of a "mini" form...
4
by: Eric | last post by:
How can I dynamically assign an event to an element? I have tried : (myelement is a text input) document.getElementById('myelement').onKeyUp = "myfnc(param1,param2,param3)"; ...
3
by: Andrew Dodgshun | last post by:
I have 2 grids - one shows a list of table names in a database and when you click on a table name the other grid dynamically populates the grid with the table contents. My problem is that I cannot...
4
by: vertigo | last post by:
Hello I need to create some objects durring program execution - but it's names are dynamically generated (depends on parameters). How can i do it ? Thanx Michal
4
by: Daniel Nogradi | last post by:
Is it possible to have method names of a class generated somehow dynamically? More precisely, at the time of writing a program that contains a class definition I don't know what the names of its...
2
by: dreamer29 | last post by:
I want to find out the unused function names from the object files that are dynamically linked later.the object files are generated from C code. Please tell me some tool to generate the call...
9
by: netasp | last post by:
hi all, how can I populate one aspx form when page is loading based on page ID? for example: loading page A (to search for VB code) would display labels and texboxes, dropdown lists all related...
9
by: Dahak | last post by:
I'm trying to generate dynamic functions to use as separate callbacks for an AJAX API call. The API doesn't seem to allow for the inclusion of any parameters in the callback, so I can't...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.