Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamic Javascript name

 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I will only know the names of Javascript functions at runtime. Is there a way to do it? Example:

function callit(num) {
// if num = 1 I want call function myfunction_1
// if num = 2 I want call function myfunction_2
// ...
// if num = n I want call function myfunction_n


}

How to do it?

Thanks!
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65227
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just looks like a series of ifs to me.

What do you mean by "at runtime"? You're not explaining this very well.
 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bear.

I want make a function name at runtime:

var func = "myFunction" + num;
func();

This does not work.

This will work : (but I need 1000 to be attached at runtime)

var func = myFunction1000;
func();

function myFunction999() {}
function myFunction1000() {}
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65227
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are the functions already defined? If so, calling a function whose name is in a string variable is easy:

 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks bear.
It works!
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65227
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Make sure you understand why it works. If not, ask...
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do the functions do? I find it unlikely this can't be done more cleanly, but without the functionality being defined it's hard to say.
 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks bear.

I figure your window[] contains references to all functions and other objects as well.
I was wondering where to find materials to study this a little more. I have used Javascript a few years and have several Javascript books but I did not know this window[] thing.


Thanks David. yes it is a little weired the way I was coding like that. But sometimes...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic