Intermediate JavaScript: assign a function with its parameter to a variable and execute later

I would like to add the comment as answer

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();

Just build the function you need and store it in a variable:

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

You could even make a function to build your functions if you wanted to vary the string:

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

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

Tags:

Javascript