473,686 Members | 3,394 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

calling a function whose name is passed as an argument

Say I have this

foo = function() {
// blah
};

bar = fuction(fnName) {
/* If fnName equalled "foo"
* How do I test that foo, as a function,
* exists and then, if it exists, call it?
*/

// I tried testing with this
if (typeof window[fnName] != 'undefined') {
/* but a variable of the same name would
* also be true wouldn't?
*/
}
};

Andrew Poulos
Aug 11 '08 #1
7 1711
On Aug 11, 12:19 pm, Andrew Poulos <ap_p...@hotmai l.comwrote:
Say I have this

foo = function() {
// blah

};

bar = fuction(fnName) {
/* If fnName equalled "foo"
* How do I test that foo, as a function,
* exists and then, if it exists, call it?
*/
Are you REALLY passing the function by name? Most people would pass it
by reference.
// I tried testing with this
if (typeof window[fnName] != 'undefined') {
Assuming you're passing it by reference (its unthinkable otherwise)
have you tried:

if (fn && fn instanceof Function) {
fn();
}
Aug 11 '08 #2
slebetman wrote:
On Aug 11, 12:19 pm, Andrew Poulos <ap_p...@hotmai l.comwrote:
>Say I have this

foo = function() {
// blah

};

bar = fuction(fnName) {
/* If fnName equalled "foo"
* How do I test that foo, as a function,
* exists and then, if it exists, call it?
*/

Are you REALLY passing the function by name? Most people would pass it
by reference.
> // I tried testing with this
if (typeof window[fnName] != 'undefined') {

Assuming you're passing it by reference (its unthinkable otherwise)
have you tried:

if (fn && fn instanceof Function) {
fn();
}
Adapted your example for function name strings (because Andrew was very
clear about wanting to pass the function name as a string in his example):

if(window[fn] && window[fn] instanceof Function){
return window[fn]();
}

I've had to do this exact thing, but I'm not worried about the risk of
variables existing with the same name (due to some extremely unique
function names) so I just do this:

if(window[fn]) return window[fn]();
Aug 11 '08 #3
On Aug 11, 3:34*pm, Stevo <n...@mail.inva lidwrote:
slebetman wrote:
On Aug 11, 12:19 pm, Andrew Poulos <ap_p...@hotmai l.comwrote:
Say I have this
foo = function() {
* *// blah
};
bar = fuction(fnName) {
* */* If fnName equalled "foo"
* * * How do I test that foo, as a function,
* * * exists and then, if it exists, call it?
* * */
Are you REALLY passing the function by name? Most people would pass it
by reference.
* *// I tried testing with this
* *if (typeof window[fnName] != 'undefined') {
Assuming you're passing it by reference (its unthinkable otherwise)
have you tried:
* if (fn && fn instanceof Function) {
* * fn();
* }

Adapted your example for function name strings (because Andrew was very
clear about wanting to pass the function name as a string in his example):

if(window[fn] && window[fn] instanceof Function){
* *return window[fn]();
}
There is a long and detailed thread about this:

<URL:
http://groups.google.com.au/group/co...96aa7cb290ec3c
>

A javscript function can be defined as an object that implements an
internal [[Call]] method, i.e. that it can be called. The difficulty
is that you can't directly test for that other than actually
attempting to call it. While it is required that native functions
return true for:

typeof functionName === 'function'
there is no such requirement for host objects that can be called. For
example:

alert(typeof document.getEle mentById);

shows "function" in Firefox and "object" in IE, similarly:

alert( document.getEle mentById instanceof Function);

returns true in Firefox and false in IE.

So testing with either instanceof or typeof is only suitable if the
object to be tested is known to be a native object.

I've had to do this exact thing, but I'm not worried about the risk of
variables existing with the same name (due to some extremely unique
function names) so I just do this:

if(window[fn]) return window[fn]();
or remove the function wrapper and use:

fn && fn();

Which is probably suitable in most cases provided adequate testing
(i.e. unit, system and acceptance) is performed and developers are
aware of the limitations.
--
Rob
Aug 11 '08 #4
RobG wrote:
On Aug 11, 3:34 pm, Stevo <n...@mail.inva lidwrote:
>slebetman wrote:
>>On Aug 11, 12:19 pm, Andrew Poulos <ap_p...@hotmai l.comwrote:
There is a long and detailed thread about this:

<URL:
http://groups.google.com.au/group/co...96aa7cb290ec3c
I was almost going to recommend the jQuery 'isFunction' function here,
as a joke. e.g. This problem has already been solved. See
jQuery.isFuncti on.
>
A javscript function can be defined as an object that implements an
internal [[Call]] method, i.e. that it can be called. The difficulty
is that you can't directly test for that other than actually
attempting to call it. While it is required that native functions
return true for:

typeof functionName === 'function'

Just because something is callable doesn't mean it is a function.

"is a Function" can be roughly translated to Function.protot ype is on
the object's prototype chain.

To determine that, instanceof and isPrototypeOf could be used. Except
for frames, because a function in an IFRAME doesn't have the parent
window's Function.protot ype in its prototype chain, so a cross-frame
test would fail.

An object that implements [[Call]] isn't necessarily a Function. That's
what David spent many long replies trying to explain to Thomas, who
seemed to not understand the intent of David's isFunction.

The purpose of knowing if something is a function, rather than is
callable, seems to be to know if you can call 'call' or 'apply' directly
on that object.

Fortunately, isFunction isn't necessary and typeof is really all you
need (see below).
there is no such requirement for host objects that can be called. For
example:

alert(typeof document.getEle mentById);

shows "function" in Firefox and "object" in IE, similarly:

alert( document.getEle mentById instanceof Function);

returns true in Firefox and false in IE.

So testing with either instanceof or typeof is only suitable if the
object to be tested is known to be a native object.
There is no way to determine if a Host object is callable, other than to
try and call it, though that may result in Error. It would have been
better if the implementations (MSIE) had followed the spirit of the
typeof operator for Host objects. For example, in IE, getElementById is
an object that implements [[Call]].

Function.protot ype.call.call(d ocument.getElem entById, document, "x");

Works in IE. This could only be possible if either:

A) document.getEle mentById implements [[Call]].
B) JScript has a special implementation of Function.protot ype.call to
handle Host object.

Either way, we can still use the callable check with the typeof operator:

if(typeof x == "function")
Function.protot ype.call.call(x , context, "x");

Garrett
>
--
Rob
Aug 11 '08 #5
dhtml wrote:
RobG wrote:
>On Aug 11, 3:34 pm, Stevo <n...@mail.inva lidwrote:
>>slebetman wrote:
On Aug 11, 12:19 pm, Andrew Poulos <ap_p...@hotmai l.comwrote:

There is a long and detailed thread about this:

<URL:
http://groups.google.com.au/group/co...96aa7cb290ec3c

I was almost going to recommend the jQuery 'isFunction' function here,
as a joke. e.g. This problem has already been solved. See
jQuery.isFuncti on.
I thought you might.
>A javscript function can be defined as an object that implements an
internal [[Call]] method, i.e. that it can be called. The difficulty
is that you can't directly test for that other than actually
attempting to call it. While it is required that native functions
return true for:

typeof functionName === 'function'

Just because something is callable doesn't mean it is a function.
And that was not what was said. However, the opposite is likely to be true.
"is a Function" can be roughly translated to Function.protot ype is on
the object's prototype chain.
Very roughly. One could also say you are mistaken here.
To determine that, instanceof and isPrototypeOf could be used.
But that would be foolish, because (you are contradicting yourself in the
next paragraph):
An object that implements [[Call]] isn't necessarily a Function.
It is not necessary that it is a function as long as it can be called.
That's what David spent many long replies trying to explain to Thomas, who
seemed to not understand the intent of David's isFunction.
That is what you still do not get.
The purpose of knowing if something is a function, rather than is
callable, seems to be to know if you can call 'call' or 'apply' directly
on that object.
True, but one would also need to determine whether the object has such
methods. Which appears to be something of a chicken-and-the-egg problem.
Fortunately, isFunction isn't necessary and typeof is really all you
need (see below).
It is not, of course.
>there is no such requirement for host objects that can be called. For
example:

alert(typeof document.getEle mentById);

shows "function" in Firefox and "object" in IE, similarly:

alert( document.getEle mentById instanceof Function);

returns true in Firefox and false in IE.

So testing with either instanceof or typeof is only suitable if the
object to be tested is known to be a native object.

There is no way to determine if a Host object is callable, other than to
try and call it, though that may result in Error.
There you contradict yourself again.
PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm>
Aug 11 '08 #6
Thomas 'PointedEars' Lahn wrote:
dhtml wrote:
>RobG wrote:
>>A javscript function can be defined as an object that implements an
internal [[Call]] method, i.e. that it can be called. The difficulty
is that you can't directly test for that other than actually
attempting to call it. While it is required that native functions
return true for:

typeof functionName === 'function'
Just because something is callable doesn't mean it is a function.

And that was not what was said. However, the opposite is likely to be true.
s/opposite/reverse/
PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f8************ *******@news.de mon.co.uk>
Aug 11 '08 #7
In comp.lang.javas cript message <g7************ *@news.t-online.com>,
Mon, 11 Aug 2008 07:34:58, Stevo <no@mail.invali dposted:
>Adapted your example for function name strings (because Andrew was very
clear about wanting to pass the function name as a string in his
example):

if(window[fn] && window[fn] instanceof Function){
return window[fn]();
}
That code is not entirely satisfactory as an example. The programmer
has a clear expectation of calling a function. If the function *IS*
always considered callable by the IF, then the IF is not needed.
Otherwise, if the function is not considered callable, the programmer's
expectation is silently unfulfilled.

But the programmer's expectation is probably worthwhile; and its absence
may not always be perceived on test and may be deleterious in operation.

Therefore the IF, in the example, requires an ELSE. The example cannot
tell whether there should be a message to the user, an alternate piece
of code, or just nothing; but it can be written like

if (window[fn] && window[fn] instanceof Function) {
return window[fn]() } ; else { DealWithFailure () }

which reminds the programmer that at least some thought is needed.
Remember that examples should be aimed at the less able programmer; and
he may well be so keen on working on the "callable" case as to forget
the "non-callable" case.

--
(c) John Stockton, nr London UK. ?@merlyn.demon. co.uk Turnpike v6.05 MIME.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/&c., FAQqy topics & links;
<URL:http://www.merlyn.demo n.co.uk/clpb-faq.txt RAH Prins : c.l.p.b mFAQ;
<URL:ftp://garbo.uwasa.fi/pc/link/tsfaqp.zipTimo Salmi's Turbo Pascal FAQ.
Aug 12 '08 #8

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

Similar topics

5
2467
by: Alex Lyman | last post by:
Does anyone have any code handy (or know what a good direction for me to head in), to call functions, if you have an address of the function, its declspec (for my app, it's limited to _stdcall and thiscall), and what parameters it expects? I know all about the argument ordering on the stack, but I don't really know enough ASM to work with it. Does anyone out there know of a cheap way to do it in more standardized C++? (efficiency doesn't...
8
2958
by: Muthu | last post by:
I've read calling conventions to be the order(reverse or forward) in which the parameters are being read & understood by compilers. For ex. the following function. int Add(int p1, int p2, int p3); The parameters here can be read either in the forward order from p1 till p3 or reverse order from p3 till p1. Can anyone explain what is the advantage/disadvantage of either of
17
3594
by: Charles Sullivan | last post by:
The library function 'qsort' is declared thus: void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *)); If in my code I write: int cmp_fcn(...); int (*fcmp)() = &cmp_fcn; qsort(..., fcmp); then everything works. But if instead I code qsort as:
18
4346
by: John Friedland | last post by:
My problem: I need to call (from C code) an arbitrary C library function, but I don't know until runtime what the function name is, how many parameters are required, and what the parameters are. I can use dlopen/whatever to convert the function name into a pointer to that function, but actually calling it, with the right number of parameters, isn't easy. As far as I can see, there are only two solutions: 1) This one is portable. If...
15
22839
by: dspfun | last post by:
Hi, Is it possible to print the function name of the calling function? For example, f1() and f2() both calls f3(), in f3() I would like to print the name of the function calling f3() which could either be f1() or f2(). BRs!
6
2990
by: Sagari | last post by:
Greetings, Can someone suggest an efficient way of calling method whose name is passed in a variable? Given something like: class X: #... def a(self):
10
3249
by: sulekhasweety | last post by:
Hi, the following is the definition for calling convention ,which I have seen in a text book, can anyone give a more detailed explanation in terms of ANSI - C "the requirements that a programming system places on how a procedure is called and how data is passed between a calling program and procedures are called calling conventions"
30
2728
by: Adam | last post by:
Hi, I have a simple printf-like function: int print(const char *format, ...) { char buffer; va_list argptr; int i;
0
13335
amitpatel66
by: amitpatel66 | last post by:
There is always a requirement that in Oracle Applications, the Concurrent Program need to be execute programatically based on certain conditions/validations: Concurrent programs can be executed programatically either from UNIX or Oracle PLSQL. In this Section, I will be explaining about calling a Concurrent program from UNIX using the CONCSUB Command. Pre-requisite: 1. Concurrent Program should be registered in oracle Applications...
0
8516
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,...
1
8768
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
8778
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
7599
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
5796
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
4308
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
4532
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2205
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1934
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.