473,770 Members | 2,135 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I have one function call another function dynamically?


Folks,

I'm sure this can be done legally, and not thru tricks of the trade - I
hope someone can help.

I'm writing a 'tool' (a function) which can be used generically in any
of my projects. When it completes, it can call a success, or a failure
function. The names of these success, or failure functions will differ,
and I'd like to know how I can pass the name of a function to my tool,
and how my tool can call the function, using that name...

Roughly speaking I want to have something like

function my_engine(succe ss_function_nam e, failure_functio n_name)
{
// Processing code here chews data

// Then...
if(myResult==tr ue)
{ success_functio n_name(); }
else
{ failure_functio n_name(); }
}

Anybody got any ideas/suggestions? I'm sure there was a js method that
I could use but I can't find reference to it in my O'Reilly JavaScript
pocket reference...

All help, via the newsgroup (so all can learn) will be greatly appreciated,

Thanks,
Randell D.
Jul 23 '05
39 6553
VK wrote:
Are you saying it is not valid JavaScript?

*Roughly* that.

As such Function will be evaluated on each call, it's performance is
lower than with standard function(). So it's suggested to use it only
if you really need to create run-time functions from the scratch.


Yes, that is exactly what he asked for.
name -> function call
It could not have been done using a literal function to my knowledge.

Anyway,
eval(name+"()")
is a better solution.
Jul 23 '05 #11
Yann-Erwan Perio wrote:
Using "eval" as property accessing technique isn't really a good
practice, in the posted case the function is called from within a
function iself called directly, so something like
this[name]();
would be a better solution:-)


Ahh interesting. So many ways to achieve something in Javascript :)
Jul 23 '05 #12
Michael Winter wrote:
Anyway,
eval(name+"()")
is a better solution.

No, it isn't. Passing a function object reference is much better, as
David describes, and it's what the OP should use.


Yes, but that was not what he asked for.
Jul 23 '05 #13
On 15/07/2005 12:37, Robert wrote:
Michael Winter wrote:
[...] Passing a function object reference is much better [...]


Yes, but that was not what he asked for.


He asked how to have one function call another. His current approach is
to pass the name of that function, but I don't see why that should be
set in stone, particularly if there's a better way.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #14
Robert wrote:
VK wrote:
Are you saying it is not valid JavaScript?


*Roughly* that.

As such Function will be evaluated on each call, it's performance is
lower than with standard function(). So it's suggested to use it only
if you really need to create run-time functions from the scratch.

Yes, that is exactly what he asked for.
name -> function call
It could not have been done using a literal function to my knowledge.

Anyway,
eval(name+"()")
is a better solution.


NO.

window[name+'()']

is a better solution.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Jul 23 '05 #15
Randell D. wrote:
I'd like to know how I can pass the name of a
function to my tool, and how my tool can call the function, using that
name...


Wow, all these posts and no one answered your question :)

Passing a reference to a function is best, but not always possible or
practical.

Since functions are just properties of the window object, you can do:

function callfunc(name) {
if (typeof(window[name])=="function") {
window[name]();
}
}

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Jul 23 '05 #16
Matt Kruse wrote:
Randell D. wrote:
I'd like to know how I can pass the name of a
function to my tool, and how my tool can call the function, using that
name...

Wow, all these posts and no one answered your question :)


That's not fair! I answered... just wasn't a very efficient way to do it :p
Jul 23 '05 #17
Randy Webb wrote:
window[name+'()']

is a better solution.


I'm now reluctant to submit window[]-based solutions, for at least two
reasons:
- window[] implies that the host is a browser; using "this" would work
on all browsers, provided the function is called as a member of the
global object,
- window[] implies that the conception relies on global functions, which
generally indicates a namespace pollution, therefore often a lazy
conception.

Anyway, in your example you have to put the parentheses outside of the
identifier, otherwise this won't work.

The following should help the OP into misunderstandin g everything:-)

---
window["foo()"]=foo;
function foo(){alert("He llo, World!")};
function test(name){
this[name+"()"]();
}

test("foo");
---
Cheers,
Yep.
Jul 23 '05 #18
Yann-Erwan Perio wrote:
- window[] implies that the host is a browser; using "this" would work
on all browsers, provided the function is called as a member of the
global object,
Using 'this' is highly sensitive to the calling environment also. For most
situations, referencing window[name]() will work while this[name]() might
not.
- window[] implies that the conception relies on global functions,
which generally indicates a namespace pollution, therefore often a
lazy conception.


I disagree.

Most people developing javascript are not experts at the language by any
means. Most code does not make use of closures or inner functions, but
instead has a bunch of global functions.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Jul 23 '05 #19
Matt Kruse wrote:

Hi,
- window[] implies that the host is a browser; using "this" would work
on all browsers, provided the function is called as a member of the
global object,
Using 'this' is highly sensitive to the calling environment also. For most
situations, referencing window[name]() will work while this[name]() might
not.
As you say, the "this" value depends on the way the function is called:
if called as a method, then the "this" value will be the reference of
the object of which it is the method, if called as a function then the
"this" value will be a reference to the global object.

So if you want a function generic enough to be called as a member of
different objects (global object, custom object), and only operate with
the global object for the "this" value, then indeed referencing "window"
directly would be a good option (while I'd prefer, personally, use a
construct with an inner function returning the global object).

However I feel that, when calling a function, the "this" value inside
should be already known and should not depend on how the function is
called (an external parameter of the function, lack of encapsulation).
- window[] implies that the conception relies on global functions,
which generally indicates a namespace pollution, therefore often a
lazy conception.

I disagree.

Most people developing javascript are not experts at the language by any
means. Most code does not make use of closures or inner functions, but
instead has a bunch of global functions.


Your argument, AIUI, is strange you know; you say you disagree that
global functions indicate a lazy conception, and then you justify the
point by precising that the guys using the "global functions" approaches
are not javascript experts.

What should I conclude from this? Should I trust so-called professionals
who can only use global functions, and don't even understand the
paradigm of the language they're using, to be skilled enough to provide
me with quality code?

Or would you rather defend that conceptions based on global functions
can be as good as conceptions using the javascript paradigm to its full?
Regards,
Yep.
Jul 23 '05 #20

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

Similar topics

2
1832
by: Joe | last post by:
I have 3 functions: ClientInfoA is doing something ClientInfoB is doing something SelectFunction2Run is a function to determine which function needed to run based on the value of the variable Method2Run. If the clientType is A, it would run ClientInfoA function. If it is clientType B, it would run the ClientInfoB function. Based on the value of Method2Run, how would I run the function dynamically? I know that there are many ways not to...
8
4833
by: Falc2199 | last post by:
Hi, Does anyone know how to make this work? var sectionId = 5; repeat_section_sectionId(); function repeat_section_5(){ alert("firing"); }
5
651
by: Tony Johansson | last post by:
Hello experts! Why is not possible to have virtual static members Many thnakn //Tony
4
4291
by: John | last post by:
Hi all, This really is quite an urgent matter. I have a page with multiple, dynamically-loaded user controls and when a user clicks on a button, the whole form is submitted. Now at this stage I know I need to call a function that will save data but I'm not sure exactly when to call this function. I've tried two ways and both seem to have 'gotcha's':
9
3744
by: Kishor | last post by:
Hi all, I am Using VB.Net for developing my application. I am now needed help. In this project I have to execute some function, but I cannot call them directly using function name, I wanted to execute this function dynamically. So I have a function list in database written as a string. I am now looking for function or mechanism which will execute function dynamically. I am here Giving a example.
12
5797
by: leaf | last post by:
Hi, How to call function at runtime, based on a struct that contains the information for the function call: struct func_to_call { int function_id; // function id to call unsigned int nparams; // number of parameters unsigned long* parameter; // the parameter(s) to pass }
5
2947
by: Sakcee | last post by:
python provides a great way of dynamically creating fuctions calls and class names from string a function/class name can be stored as string and called/initilzed e.g def foo(a,b): return a+b
1
2284
by: johnjsforum | last post by:
Buddies, I have a web page to create HTML buttons dynamically as in the “formDivColorPicker” function //////////////////////////////////////////////////////////////////////////////////// version 1 : using global variables ////////////////////////////////////////////////////////////////// var _textField, _divColorPicker; // global vars window.onload = function() { _textField = document.getElementById('htxaMessage'); // fill...
32
5679
by: copx | last post by:
Why doesn't the C standard include generic function pointers? I use function pointers a lot and the lack of generic ones is not so cool. There is a common compiler extension (supported by GCC and lccwin32 for example) which I consider to be perfectly reasonable: you can cast every kind of function pointer to a void pointer and void pointers to any kind of function pointer. This follows the general "generics through void scheme" of C....
3
3357
by: ataxia1 | last post by:
For the project I'm working on, I need to dynamically call one of several functions (which are dynamically named by asp.net). How do I call a function when I have the function name in a string? A case statement is not an option, because the function names are dynamic. function function1() { ... } function function2() { ... } var functionName = 'function1'
0
9591
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9425
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10228
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10057
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9869
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6676
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5449
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3970
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3575
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.