Contact!

Calling a function using a string: JavaScript

eval() alternative

In JavaScript it is possible to call a function using a string. All you need to know is the object the function resides in and the name of the function as a string.

You could do this using eval(), but apparently it is a big ‘no-no’ for security reasons. Here is a safer approach:

function dave(message) {
    alert(message);
}

// object[functionString](args)
window['dave']('hello');

Clean and simple, without opening eval(“Pandora’s Box”).

Join the discussion!

You might like: