Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

like image 998
airnet Avatar asked Oct 15 '11 06:10

airnet


People also ask

Can you assign a function to a variable in JavaScript?

It is possible to use a function expression and assign it to a regular variable, e.g. const factorial = function(n) {...} . But the function declaration function factorial(n) is compact (no need for const and = ). An important property of the function declaration is its hoisting mechanism.

How do you assign a function to a variable?

Method 1: Assign Function Object to New Variable Name A simple way to accomplish the task is to create a new variable name g and assign the function object f to the new variable with the statement f = g.

What is function () () in JavaScript?

A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.

Is JavaScript function can perform in any checking on parameter values?

A JavaScript function does not perform any checking on parameter values (arguments).


2 Answers

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();
like image 78
Deeptechtons Avatar answered Sep 20 '22 18:09

Deeptechtons


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"
like image 28
mu is too short Avatar answered Sep 19 '22 18:09

mu is too short