Javascript store function with parameters in variable
I have the following:
I want to store functions with several parameters, and bind them to buttons later when the DOM is loaded
It's not really working since steps[i] contains do(array[i].something, array[i].wow, i); instead of do('bob', 'john', 1) for example I have tried using the .apply javascript function but it will execute in the loop, instead of storing them
asked Feb 28, 2012 at 17:20 2 Closures can help you here. Here's one solution to the first bit of code:
There's no "block scope" in Javascript, just function scope. With your code, each function you pushed into the answered Feb 28, 2012 at 17:23
Paul BrunoPaul Bruno 1,8761 gold badge17 silver badges26 bronze badges 5 Use
See the docs here. Note under the heading Compatability, it explains how to make sure this function will work on all your target browsers (even old verison of IE). You can just copy and paste the code there. answered Feb 28, 2012 at 17:26
benekastahbenekastah 5,5611 gold badge34 silver badges47 bronze badges 2
answered Feb 28, 2012 at 17:32
TomalakTomalak 326k66 gold badges515 silver badges618 bronze badges
answered Feb 28, 2012 at 17:30
NikNik 3831 gold badge4 silver badges15 bronze badges 1 Functions are one of the fundamental building blocks 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. To use a function, you must define it somewhere in the scope from which you wish to call it. See also the exhaustive reference chapter about JavaScript functions to get to know the details. A function definition (also called a function declaration, or function statement) consists of the For example, the following code defines a simple function named The function Parameters are essentially passed to functions by value — so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function, the change is not reflected globally or in the code which called that function. When you pass an object as a parameter, if the function changes the object's properties, that change is visible outside the function, as shown in the following example:
When you pass an array as a parameter, if the function changes any of the array's values, that change is visible outside the function, as shown in the following example:
Function expressionsWhile the function declaration above is syntactically a statement, functions can also be created by a function expression. Such a function can be
anonymous; it does not have to have a name. For example, the function
However, a name can be provided with a function expression. Providing a name allows the function to refer to itself, and also makes it easier to identify the function in a debugger's stack traces:
Function expressions are convenient when passing a function as an argument to another function. The following example
shows a
In the following code, the function receives a function defined by a function expression and executes it for every element of the array received as a second argument:
Function returns: In JavaScript, a function can be defined based on a condition. For example, the following function definition defines
In addition to defining functions as described here, you can also use the A method is a function that is a property of an object. Read more about objects and methods in Working with objects. Calling functionsDefining a function does not execute it. Defining it names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the function The preceding statement calls the function with an argument of Functions must be in scope when they are called, but the function declaration can be hoisted (appear below the call in the code), as in this example:
The scope of a function is the function in which it is declared (or the entire program, if it is declared at the top level). Note: This works only when defining the function using the above syntax (i.e., This means that function hoisting only works with function declarations—not with function expressions.
The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The A function can call itself. For example, here is a function that computes factorials recursively:
You could then compute the factorials of
There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime. It turns out that
functions are themselves objects — and in turn, these objects have methods. (See the Function scopeVariables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function, and any other variables to which the parent function has access.
Scope and the function stackRecursionA function can refer to and call itself. There are three ways for a function to refer to itself:
For example, consider the following function definition:
Within the function body, the following are all equivalent:
A function that calls itself is called a recursive function. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). For example, consider the following loop:
It can be converted into a recursive function declaration, followed by a call to that function:
However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (such as the DOM) is easier via recursion:
Compared to the function It is possible to convert any recursive algorithm to a non-recursive one, but the logic is often much more complex, and doing so requires the use of a stack. In fact, recursion itself uses a stack: the function stack. The stack-like behavior can be seen in the following example:
Nested functions and closuresYou may nest a function within another function. The nested (inner) function is private to its containing (outer) function. It also forms a closure. A closure is an expression (most commonly, a function) that can have free variables together with an environment that binds those variables (that "closes" the expression). Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function. To summarize:
The following example shows nested functions:
Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:
Preservation of variablesNotice how This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them. Multiply-nested functionsFunctions can be multiply-nested. For example:
Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called scope chaining. (The reason it is called "chaining" is explained later.) Consider the following example:
In this example, This can be done because:
The reverse, however, is not true. Name conflictsWhen two arguments or variables in the scopes of a closure have the same name, there is a name conflict. More nested scopes take precedence. So, the innermost scope takes the highest precedence, while the outermost scope takes the lowest. This is the scope chain. The first on the chain is the innermost scope, and the last is the outermost scope. Consider the following:
The name conflict happens at the statement ClosuresClosures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to). However, the outer function does not have access to the variables and functions defined inside the inner function. This provides a sort of encapsulation for the variables of the inner function. Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the duration of the outer function execution, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function.
It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.
In the code above, the
Note: There are a number of pitfalls to watch out for when using closures! If an enclosed function defines a variable with the same name as a variable in the outer scope, then there is no way to refer to the variable in the outer scope again. (The inner scope variable "overrides" the outer one, until the program exits the inner scope. It can be thought of as a name conflict.)
Using the arguments objectThe arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows: where Using the For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:
You can pass any number of arguments to this function, and it concatenates each argument into a string "list":
Note: The See the Function parametersThere are two special kinds of parameter syntax: default parameters and rest parameters. Default parametersIn JavaScript, parameters of functions default to In the past, the general strategy for setting defaults was to test parameter values in the body of the function and
assign a value if they are In the following example, if no value is provided for
With default parameters, a manual check in the function body is no longer necessary. You can put
For more details, see default parameters in the reference. Rest parametersThe rest parameter syntax allows us to represent an indefinite number of arguments as an array. In the following example, the function
Arrow functionsAn arrow function expression (also called a fat arrow to distinguish from a hypothetical Two factors influenced the introduction of arrow functions: shorter functions and non-binding of Shorter functionsIn some functional patterns, shorter functions are welcome. Compare:
No separate thisUntil arrow functions, every new function defined its own
In ECMAScript 3/5, this issue was fixed by assigning the value in
Alternatively, a bound function could be created so that the proper An
arrow function does not have its own
Predefined functionsJavaScript has several top-level, built-in functions: eval() The isFinite() The global isNaN() The
parseFloat() The parseInt() The decodeURI() The decodeURIComponent() The encodeURI() The encodeURIComponent() The escape() The deprecated unescape() The deprecated
Can I store a function in a variable JavaScript?In JavaScript, functions are called Function Objects because they are objects. Just like objects, functions have properties and methods, they can be stored in a variable or an array, and be passed as arguments to other functions.
Can a JavaScript function have parameters?A JavaScript function can have any number of parameters. The 3 functions above were called with the same number of arguments as the number of parameters. But you can call a function with fewer arguments than the number of parameters.
How do you put a function into a variable?we put the function in a variable if inside the function block we use the return method: var multiplyTwo = function (a) { return a * 2; };
Can JavaScript functions have properties?In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called.
|