473,378 Members | 1,544 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

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 1691
On Aug 11, 12:19 pm, Andrew Poulos <ap_p...@hotmail.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...@hotmail.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.invalidwrote:
slebetman wrote:
On Aug 11, 12:19 pm, Andrew Poulos <ap_p...@hotmail.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.getElementById);

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

alert( document.getElementById 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.invalidwrote:
>slebetman wrote:
>>On Aug 11, 12:19 pm, Andrew Poulos <ap_p...@hotmail.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.isFunction.
>
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.prototype 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.prototype 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.getElementById);

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

alert( document.getElementById 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.prototype.call.call(document.getElementBy Id, document, "x");

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

A) document.getElementById implements [[Call]].
B) JScript has a special implementation of Function.prototype.call to
handle Host object.

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

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

Garrett
>
--
Rob
Aug 11 '08 #5
dhtml wrote:
RobG wrote:
>On Aug 11, 3:34 pm, Stevo <n...@mail.invalidwrote:
>>slebetman wrote:
On Aug 11, 12:19 pm, Andrew Poulos <ap_p...@hotmail.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.isFunction.
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.prototype 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.getElementById);

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

alert( document.getElementById 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.demon.co.uk>
Aug 11 '08 #7
In comp.lang.javascript message <g7*************@news.t-online.com>,
Mon, 11 Aug 2008 07:34:58, Stevo <no@mail.invalidposted:
>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.demon.co.uk/TP/BP/Delphi/&c., FAQqy topics & links;
<URL:http://www.merlyn.demon.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
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...
8
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...
17
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...
18
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...
15
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...
6
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
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...
30
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
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.