ChetOS.net

JavaScript tidbit

Lets say you want to execute a function, but you don't want to determine which function to call until runtime.  The appropriate method is to do this:

var methodName = prompt('Enter a JavaScript function name.');
eval(methodName);


Would get a popup box with the "Enter some JavaScript" text and an input box.  He could then type in alert('Hello World'); and it would be executed.

Lets take this a bit further.  What if you wanted the server to be able to tell the browser what to do using JavaScript at runtime?  Well you could use the new fangled AJAX to ask the server what to do, and then have the server reply with a function.  It would work exactly the same way, only it would be the server rather than the user supplying the methodName.

This brings up a interesting thing though... the server cannot know for certain if the function exists.  Assume the server returns response_populateSelectList(), if the client didn't implement it for some reason (or if it was misspelled) then it would "throw an error".  I say it like that because throwing an error in Internet Explorer is nothing like it is in a normal environment.  All you get is a notification that an error occurred on some line.  That line number can be (and usually is on very large projects) wrong.  Futhermore, it won't tell if you which source file it was in.

There are two methods for determining if a method exists.

if (alert) {
      alert('true');
}

if ((typeof alert == 'function') || (typeof alert == 'object')) {
      alert('true');
}


The first method works for most built-in objects.  The second works for user-defined functions as well.

However, going back to our origional example.
var methodName = prompt('Enter a JavaScript function name.');
eval(methodName);


The variable methodName is a string, it is not a function, so doing typeof methodName will return string not function.  You have to use the eval() method to your advantage and have it check for you.  Also, chances are your function is a sub-set of the window object so you have to prefix it with the declaration.  Hence:
if (!('function' == eval('typeof window.' + methodName))) {
      alert('Invalid function call: ' + methodName);
      return false;
}


Now, when you pass an invalid function it will tell you, rather than just having to guess exactly what went wrong.

Oh, while we are on the subject.  If you ever want to pass parameters to your method:

var methodName = 'alert';
var parameterList = 'Hello World';
eval(methodName + '(parameterList);');
Posted by Chet at 4:36 PM

Comments

No Comments have been Posted.

Post a Comment

Feel Free To Share Your Thoughts
You can use [b], [u], [i], and [url]
Optional
Name
Website
© 2013 Chet Zema π