Variable functions in javascript

So i needed a way to elegantly handle incoming requests and route them to appropriate functions. I had an object comming in with some variables – one specifying the method to execute and the other(s) containing relevant data. I could use a switch statement, but i need to keep the script as small as possible (and i want something more dynamic).

In PHP i’d use variable functions -

function sheep() {...}

$cow = "sheep";

$cow() // Executes function sheep()

JS can’t handle that. So i google’d around and found a post that was quite helpful on the subject. After a slight optimisation I’ve come to this:

function sheep() { alert("behh"); }

var test = "sheep";

window[test](); // Will execute sheep()

And now i can use variable functions in javascript :)

This entry was posted in Code, JS, Programming, Tutorials. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>