To understand the functional programming principles in JavaScript, you must understand two knowledge points.
1. Calls of functions and methods in JavaScript
In JavaScript, there are two methods to call functions. The general method is to put parameters in brackets, and the other method is to put both functions and parameters in brackets. For example:
The Code is as follows:
Function test (x)
{
Alert (x );
}
Test ("hello ");
(Test) ("hello ");
// Equivalent to the following code
(Function test (x)
{
Alert (x );
}) ("Hello ");
// It is also equivalent to the following code
(Function (x)
{
Alert (x );
}) ("Hello ");
2. Anonymous Functions
An anonymous function is a function or method without a name. Anonymous functions can be considered as one-time functions. They are especially useful when you only need to use a function once. By using anonymous functions, since there are no relevant references and identifiers, they will be reclaimed after execution, so using anonymous functions is more efficient. The following is a simple comparison between an anonymous function and other referenced or identified functions:
The Code is as follows:
Function test (x)
{
Alert ("defining an identity function ");
}
Var test = function ()
{
Alert ("pointing an anonymous function to a reference ");
}
(Function ()
{
Alert ("I am an anonymous function ");
}) (); // An anonymous function has been defined and executed here.
Most languages support using functions as operation elements (parameters) for calculation. However, due to the different positioning of functions, their calculation results are not the same. When a function in JavaScript is used as a parameter, it is passed through reference. "Function parameters" are no different from common parameters. They return unique values.
The Code is as follows:
Function test (func)
{
Alert (func );
}
Test (function () {return "anonymous function (execution result) as the parameter "})());
Every variable in functional programming is generated temporarily. You can also think that: there is no variable in the function type, and any data is calculated based on actual needs according to certain rules (functions, this also solves the issue of concurrent access to atomic variables to a certain extent.