JavaScript – Use a variable for a function call

Sometimes you want to pass a function around from script to script as a string containing the function name (well maybe not, but I have some legacy code that does require this)

So if you have a function called doSomething() and you want to call it from another page, but you’ve passed it like so:

<script type="text/javascript">
function startSequence()
    {
    var nextFunction = 'doSomething';
    return nextFunction;
    }
window[startSequence()]();
</script>

So what I’m saying is the function will be placed into the Window object, so you can call it :

window[variable]();

And it obviously extends to the window.opener object.

I’m sure there are better ways, but this is handy to know I think.

Leave a Reply

Your email address will not be published.

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=""> <s> <strike> <strong>