Intermediate javascript: assign a function with its variable parameter and execute it later

I have a function in javascript:

function alertMe($a)
{
   alert($a);
}

What can I do as follows: alertMe ("Hello");

I want to set alertMe ("Hello") to the "Hello" variable with the $ func variable, and you can do this later by doing something like $ func ();

+5
source share
3 answers

I would like to add a comment as an answer

The code

//define the function
function alertMe(a) {
    //return the wrapped function
    return function () {
        alert(a);
    }
}
//declare the variable
var z = alertMe("Hello");
//invoke now
z();
+8
source

Just create the function you want and save it in a variable:

var func = function() { alertMe("Hello") };
// and later...
func();

You can even create a function to create your own functions if you want to change the line:

function buildIt(message) {
    return function() { alertMe(message) };
}

var func1 = buildIt("Hello");
var func2 = buildIt("Pancakes");
// And later...
func1(); // says "Hello"
func2(); // says "Pancakes"
+3
source

eval . :

var func = "alertMe('Hello')";
eval(func);
-3

All Articles