Entry
How to know if a function is already created (exists) in a document?
Nov 18th, 2002 05:49
Russ Locke, Mark Filipak, Dario Carnelutti,
Here are 2 valid solutions:
------------------------------------------------------------
Solution 1: (By: Russ Locke)
-----------
<html><head><script language="javascript">
function doit() {
var doneexists = (this.done == null) ? false : true;
var nopeexists = (this.nope == null) ? false : true;
alert("done = "+doneexists+" nope = "+nopeexists);
}
function done() {
alert("yippie");
}
</script></head><body onload="doit();">
</body></html>
------------------------------------------------------------
Solution 2: (by: Mark Filipak)
-----------
A function is an object and its existence can be tested just as you can
test for the existance of any object. However, you have to know where
the object is.
If the function object is a property of the global object, then this:
doesExist =
typeof(this[nameOfMyFunction])!='undefined'
? typeof(this[nameOfMyFunction])=='function'
: false;
will set a global variable, doesExist, to the appropriate value for
further processing. Note that the first test (for 'undefined') must be
done first, and only if it succeeds can you do the test for 'function',
otherwise, the code will throw an 'undefined' exception.
-----------------------------------------------
In other words, don't do this:
doesExist =
typeof(this[nameOfMyFunction])!='undefined'
&&
typeof(this[nameOfMyFunction])=='function';
-----------------------------------------------
If the function object is not a property of the global object (that is,
if it has a parent), then here's what to do:
doesExist =
typeof(parentObject[nameOfMyFunction])!='undefined'
? typeof(parentObject[nameOfMyFunction])=='function'
: false;
Here's an example test case:
//_____ SET UP EXAMPLE
parentObject = new Object;
parentObject.myFunction = function myFunction() { alert('Hello'); };
//_____ RUN EXAMPLE
nameOfMyFunction = 'myFunction';
doesExist =
typeof(parentObject[nameOfMyFunction])!='undefined'
? typeof(parentObject[nameOfMyFunction])=='function'
: false;
if (doesExist) {
alert("\
Function, "+ nameOfMyFunction +", exists as a property of \
parentObject, and its value is \
"+parentObject[nameOfMyFunction]);
}
The technique above can be adapted to search all 'parentObject's to
find, not only whether a function is the property of a particular
parent, but it can also find the parent!