473,761 Members | 1,764 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 #1
39 6550
Randell D. wrote:

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


function callFunction(na me)
{
var f = new Function(name+" ()");
f();
}

But maybe it would be more convenient to just pass the function itself
as a parameter...

Robert.
Jul 23 '05 #2
ASM
Randell D. wrote:

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(); }
try :
Function(succes s_function_name );
with calling
my_engine('succ ess', 'failure');

or
{ success_functio n_name }
or ?
{ eval(success_fu nction_name) }
and calling :
my_engine('succ ess()', 'failure()');
else
{ failure_functio n_name(); }
}


--
Stephane Moriaux et son [moins] vieux Mac
Jul 23 '05 #3
VK
> 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...


It is very simple. Just pass *function references*, not function names.

<script type="text/javascript">
function f1(fun1,fun2) {
fun1();
fun2()
}

function f2() {
alert('f2')
}

function f3() {
alert('f3');
}

function init(){
f1(f2,f3);
}

window.onload = init;
</script>

Jul 23 '05 #4
VK


Robert wrote:
function callFunction(na me)
{
var f = new Function(name+" ()");
f();
}


What a hey is that? We're talking JavaScript here, not RobertScript :-)

Do you mind at the very least:
<http://msdn.microsoft. com/library/default.asp?url =/library/en-us/script56/html/js56jsobjfuncti on.asp>

Jul 23 '05 #5
Randell D. wrote:
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...
Passing the name of a function is the wrong thing to do here. Instead you
should just pass the function itself.

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


Just do it this way:

function my_engine(succe ss_function, failure_functio n)
{
// Processing code here chews data

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

This way the functions don't actually have to be accessible through global
names, you can also use anonymous functions, or functions defined inside
other functions.

Jul 23 '05 #6
VK wrote:

Robert wrote:
function callFunction(na me)
{
var f = new Function(name+" ()");
f();
}

What a hey is that? We're talking JavaScript here, not RobertScript :-)

Do you mind at the very least:
<http://msdn.microsoft. com/library/default.asp?url =/library/en-us/script56/html/js56jsobjfuncti on.asp>


Sorry? I did suggest that passing the function reference is probably a
better idea.
But what do you find wrong with my example? Are you saying it is not
valid JavaScript?
Jul 23 '05 #7
VK
> Are you saying it is not valid JavaScript?

*Roughly* that.

var functionRef = new Function(arg1, arg2, arg3, ..., argN);

where all args except the last one treated as function arguments, and
the last one as function body.
so:

var helloWorld = new Function("alert ('Hello world!);");

equals to

function helloWorld() {
alert('Hello world!);
}
var alertType = new Function("obj", "alert(typeof(o bj));");

equals to

function alertType(obj) {
alert(typeof(ob j));
}

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.

Jul 23 '05 #8
On 15/07/2005 11:54, Robert wrote:

[snip]
It could not have been done using a literal function to my knowledge.
No, it couldn't.
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.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #9
Robert wrote:

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


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

Anyway passing the reference, as yourself and others have suggested, is
the best - the OP just wasn't probably aware that functions are
first-class objects in javascript...
Cheers,
Yep.
Jul 23 '05 #10

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
5796
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
2283
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
5677
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
9377
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
10136
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
9989
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...
1
9925
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8814
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6640
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
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3913
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
3
3509
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.