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();
.
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.
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.
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.
A JavaScript function does not perform any checking on parameter values (arguments).
I would like to add the comment as answer
//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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With