473,837 Members | 1,531 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 6574
JRS: In article <0DIBe.150880$o n1.84486@clgrps 13>, dated Fri, 15 Jul
2005 06:22:52, seen in news:comp.lang. javascript, Randell D.
<su*****@fiproj ects.moc> posted :

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


You can do that; you're passing the function as a parameter.

But the test line should be if (myResult) as comparing with true is
unnecessary.

You could also do

function Mine(X, Y, AF) {
// calculate with X Y getting answer R and result code Z
AF[Z] // call the Zth function in array AF
return R }

and call it as RR = Mine(XX, YY, [F0,F1,F2,F3,F4, F5]) which has
three parameters the last being an array of functions. You probably
won't want to, but it is illustrative to see that you can.
Sometimes I use
function FuncName(Fn) { // Fn is a function; return its name
return Fn.toString().m atch(/( \w+)/)[0] }
though it's just occurred to me that the matching may be sub-optimal -
though speed is not important as I use it.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #21
Yann-Erwan Perio wrote:
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.
To me, "lazy" means you know how to do something the right way, but choose
not to because it takes more effort. Someone who is ignorant of a more
advanced way of doing a task certainly isn't "lazy" if they do it in the
best way that they know how.
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?
Sure, why not?

Do you think most of the code written in the world is written by experts in
the languages used? Far from it. There are few experts. Most code that I've
seen is written by moderately skilled programmers. Increasingly, much code
is written by junior programmers in India or similar places. Skilled
programmers who are experts in the language they are using are very rare,
IMO.
Or would you rather defend that conceptions based on global functions
can be as good as conceptions using the javascript paradigm to its
full?


It can be a complicated issue... I understand (now even more than
previously) how to use closures and other techniques which are more advanced
than most people ever face when touching javascript. [Note that I do not
consider myself an expert in the js language, but I do consider myself much
more experienced than the average person writing javascript] But in
developing code that will be maintained, implemented, and possibly enhanced
and customized by novice javascript programmers, it seems to me like a good
choice to program in a way that they will comprehend.

If I write code that is highly compact and obfuscated by advanced language
techniques, it becomes meaningless to the average javascript programmer.
Then they'll seek out a less-complex solution which they understand, but may
be written by someone at their own skill level and have problems. Which is
better? It's not as obvious of a decision as some would like to believe,
IMO.

I guess a fundamental question is: Given two sets of code - one written in a
manner that uses the language and its features to its fullest and one which
uses global functions and procedural style - that perform the same task
effectively, is one necessarily better than the other? And is that a
subjective or objective decision? Based ono what?

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Jul 23 '05 #22
Robert wrote:
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.

I'm reading through everyone's posts at the moment - my internet acces
is restricted hence I'm taken a bit by surprise on the feedback I've got
so far. I like your solution above because I can support it - however I
also agree with some of the arguements put forward by the others... I'll
read in to things further and then decide which solution to use.

Thanks for the help

randelld
Jul 23 '05 #23
Randy Webb wrote:
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.


This use of the window object (method?) I like... I'm going to play
around with it...

And with regards to eval - My experience thus far has been to avoid
using eval where possible because of its overheads... but excusing the
performance weight, its simple, and functional...

Thanks,
randelld
Jul 23 '05 #24
VK 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...

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>

I did originally try something like this but it failed - however from
what I have learned in previous posts, it is likely to have to have
failed because of the window object... I can't recall exactly (it was
one of my earlier attempts) but I think I had a child window call a
function which then called success/failure functions that existed in the
parent window environment...

I'm still learning... however I am grateful to your response.

randelld
Jul 23 '05 #25
Duncan Booth wrote:
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.


The problem with the above solution is that I'm createing a generic tool
which won't know the names of functions to call when the results of
processing are true or false... This was my main problem - do make my
tool/function dynamic for other projects...

Thanks though for the help,
Randell D.
Jul 23 '05 #26
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 :)

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


Hmmmmm... at first I balked at your reply - but after a minute or so of
thinking, I can see what you're suggesting and again, it looks clean,
and something I feel happy that I can support. I had half an idea that
functions were objects from within a window, however I was calling them
wrongly... Using a variable name called success_functio n I had tried
doing something like

window.success_ function();

but of course this failed with an error that success_functio n didn't
exist (thus telling me that success_functio n, a variable, was not
translated).

I'm still learning - and you've just thought me something nice above,
thanks

randelld
Jul 23 '05 #27
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(); }
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.

Many Many MANY thanks to all - you've given me some food for thoughts -
My internet access is restricted at the mo' so I'll go away and work on
some of the solutions everyone has proposed, and read into them. My
main concern is writing code I can support first followed closely by
something that is environmentally friendly on the systems resources...

Thanks again, I didn't think my question would prove such a large response,

Cheers
Randell D.
Jul 23 '05 #28
Yann-Erwan Perio wrote:
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.

My internet access is restricted (which is a shame) however you're
right, I didn't know that functions are first-class objects in
javascript. I have about a years worth of javascript behind me and this
will help push my skillset further... thanks

randelld
Jul 23 '05 #29
Matt Kruse wrote:

Hi,
To me, "lazy" means you know how to do something the right way, but choose
not to because it takes more effort. Someone who is ignorant of a more
advanced way of doing a task certainly isn't "lazy" if they do it in the
best way that they know how.
Ah now I understand your point, and realise I have expressed myself
inaccurately; what I meant by "lazy" was that the underlying conception
was simplistic, poor (a truly lazy conception being the shame of the
programmer).
What should I conclude from this? Should I trust so-called
professiona ls 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?

Sure, why not?
An interesting answer, but ISTM that it is centered on what programmer I
should employ, not the quality I'm expecting.

At first I'd say that because they don't fully master the language, they
can only produce a limited solution to the problem, while an experienced
programmer would be able to produce a solution using the language at its
maximum. From a quality point of view the solution provided by the
skilled programmer is likely to be superior than the one provided by the
non-qualified programmer (whose quality would depend on the task to be
coded).

However, the real problem here is indeed a matter of expectations, i.e.
compare/estimate the difference of value and cost of the 2 solutions -
and then make the choice between the two programmers.
Do you think most of the code written in the world is written by experts in
the languages used? Far from it. There are few experts. Most code that I've
seen is written by moderately skilled programmers. Increasingly, much code
is written by junior programmers in India or similar places. Skilled
programmers who are experts in the language they are using are very rare,
IMO.
My experience so far yields the same impression.

This practice comes here for business reasons, though. The less skilled
a programmer, the lower his cost, the higher the margin you can have by
selling him to your customer (be it internal or external), the higher
the risk you're taking for your project (and therefore with your customer).

This is the art of the manager to be able to employ non-qualified guys
with qualified ones, so that he can reach the level of margins expected
by the company at a price sold by the salesman, using the experience of
his skilled employees to minimise the risk for his project.

<snip>
[Note that I do not
consider myself an expert in the js language, but I do consider myself much
more experienced than the average person writing javascript]
Given the code/advice you've been offering for years you're perfectly
entitled to:-)
But in
developing code that will be maintained, implemented, and possibly enhanced
and customized by novice javascript programmers, it seems to me like a good
choice to program in a way that they will comprehend.
This is certainly an important consideration a programmer must have when
writing code - but that's not the only one. If there's no added value in
using advanced conceptions then it'd be foolish to do so (for the
reasons you've explained, among others), however if there is a real
added value in using the language to its fullest then it'd be foolish
*not* to do so.

I understand that the average programmer may not be aware of these
techniques; it is however his responsibility/interest (and the
responsibility/interest of his management) to learn and understand them
when he comes across them, and gain the ability to re-use them.
Otherwise he's just accumulating a kind of experience that permits him
to sell himself at a better price without adding more value than the
average coder - in the end he's unlikely to be taken for the job.

<snip>
I guess a fundamental question is: Given two sets of code - one written in a
manner that uses the language and its features to its fullest and one which
uses global functions and procedural style - that perform the same task
effectively, is one necessarily better than the other? And is that a
subjective or objective decision? Based ono what?


Is that really a difficult thing to assess for someone familiar with the
two approaches? It should be easy to determine whether the conception
would benefit from data encapsulation, modularisation techniques, or
whether these techniques would simply burden the script in regards of
the task that is to be performed.

The problem, with closures, is that they aren't well-known, and are hard
to learn - which make people abandon their learning even before it's
seriously started. That's too bad, because the reward is worth the
effort, i.e. the value for the programmer, the manager and the customer
could only increase.
Regards,
Yep.
Jul 23 '05 #30

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

Similar topics

2
1835
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
4836
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
4300
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
3751
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
5805
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
2952
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
2287
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
5690
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
3363
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
9837
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
10870
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
10563
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
10621
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
9392
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
5668
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5845
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4038
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3123
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.