10

I have a function in JavaScript:

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

Which I can execute like this: alertMe("Hello");

I want to do is assign alertMe("Hello") with the "Hello" parameter to a variable $func, and be able to execute this later by doing something like $func();.

1
  • look at the answer for code now Commented Oct 15, 2011 at 6:50

3 Answers 3

18

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();
Sign up to request clarification or add additional context in comments.

2 Comments

This is using the concept of closure, I suppose.
@airnet I wouldn't call these closures, these are sort of late bound calls. closaure execute immediately without you invoking them sort of like this (function(a){alert(a);})("HelloWorld");
7

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"

1 Comment

thanks guys, I wish I could accept both of your answers..:) identical answers and what i was pretty much looking for
-4

You should use eval to execute saved function. For example:

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

1 Comment

...and a pointed tail. The use of eval is potentially unsafe and in this case, a downright dirty hack!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.