Using a string as a function name?
Hi, all,
I am trying to do something like this:
Code:
var functionName = "theFunc";
functionName ();
Obviously the above syntax won't work - instead of theFunc() getting called, I get an error.
Is this possible at all, and if so, what is the correct way to do it?
All response appreciated!
// FvW
Code:
var functionName = "theFunc";
window[functionName](); //invokes the function if it is a globally accessible function,
//which is actually a property of the window object
//To apply this technique to your own object, is the same:
var myObject = {
name : 'fooObj',
speak : function () {
alert(this.name);
}
};
var funcName = 'speak';
if (funcName in myObject && typeof myObject[funcName] == 'function') { //myObject has a property by the name of funcName's value, and it is a function
myObject[funcName]();
}
Thank you!!!!!!!!!!!! You saved my day... :-)
// FvW
Originally Posted by
frankvw
Thank you!!!!!!!!!!!! You saved my day... :-)
Well, maybe not, after all. Because what I am trying to do still won't work:
Code:
function ajaxRead (url, targetObj, updateHandler) {
var xmlObj = new XMLHttpRequest ();
xmlObj.onreadystatechange = function () {
if (xmlObj.readyState == 4) {
window [updateHandler (ajaxTarget, xmlObj.responseXML.getElementsByTagName('data')[0].firstChild.data)];
}
}
xmlObj.open ('GET', url, true);
xmlObj.send (null);
}
function ajaxUpdateObj (obj, data) {
document.getElementById(obj).innerHTML = data;
}
When I call the above with something like
Code:
ajaxRead (url, target, 'ajaxUpdateObj')
(having previously set up url and target correctly, of course) I get an error message stating that 'updateHandler is not a function'. Any ideas?
// FvW
You don't have the syntax right
window [updateHandler (ajaxTarget, xmlObj.responseXML.getElementsByTagName('data')[0].firstChild.data)
] ;
Should be:
Code:
window [updateHandler] (ajaxTarget, xmlObj.responseXML.getElementsByTagName('data')[0].firstChild.data);
Originally Posted by
astupidname
You don't have the syntax right
Indeed, that turned out to be the problem. (My Javascript skills are still rather limited.)
I've got it working now. Onece agains my thanks!!
// FvW
if you made your call ajaxRead (url, target, ajaxUpdateObj), then you can simply say:
Code:
updateHandler(ajaxTarget, xmlObj.responseXML.getElementsByTagName('data')[0].firstChild.data);
there's no reason to pass strings like that; it just slows things down, demands globals, and makes your code harder to maintain.
Functions are variables like everything else, in this regard, JavaScript is like Lisp. Rnd me shows how to deal with them as variables.
Great wit and madness are near allied, and fine a line their bounds divide.
Thread Information
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Bookmarks