This paper focuses on the functional programming of personal understanding.
Functional programming Personal Understanding is: the function as the main carrier of the programming method.
Benefits:
- More clear semantics
- High reusability
- Maintainability is good
- Limited scope and fewer side effects
Basic Functional Programming:
//capitalize the first letter of each word in an array//General WordingConst ARR = [' Apple ', ' orange ', ' pear ']; for(CONST Iincharr) {Const C= Arr[i][0]; Arr[i]= C.touppercase () + arr[i].slice (1);//Slice () returns the selected element from an existing array}console.log (arr);//Functional NotationfunctionUpperfirst (word) {returnWord[0].touppercase () + word.slice (1);}functionWordtouppercase (arr) {returnArr.map (Upperfirst);} Console.log (Wordtouppercase ([' Apple ', ' orange ', ' pear '));
Chain-Optimized
From the above functional style can be seen in the multi-layered nesting, that is, it is easy to produce horizontal extension.
Such as:
// calculate the sum of numbers // General wording Console.log ((3 + 4 + 5) * 7); // Functional Notation function sum (A, b) { return a + b;} function Mul (c, D) { return c * D;} Console.log (Mul(SUM (SUM (3, 4), 5), 7));
This situation is less readable, and we can choose other ways that are more readable, such as the following chain-optimization
//the Lodash of the optimized writing styleConst UTILS ={Chain (a) { This. _temp =A; return This; }, sum (b) { This. _temp + =b; return This; }, Mul (c) { This. _temp *=C; returnC; }, Value () {const _TEMP= This. _temp; This. _temp =undefined; return_temp; }};console.log (Utils.chain (3). SUM (4). SUM (5). Mul (7). value ());
A common functional programming model
Closed Package
A block of code that can keep local variables from being freed is called a closure
Create a closure as in the following code
// Create a closed package function Makecounter () { = 0; return function () { return k++; = Makecounter (); Console.log (counter ()); // 0Console.log (counter ()); // 1
Closures are created in terms of:
- There are two layers of functions inside and outside
- The inner layer function is referenced by the local variables of the outer layer function.
The drawbacks of closures
Persistent variables are not freed normally, memory space is consumed, and memory wastage is easy, so some additional manual cleanup mechanisms are usually required.
Personal Understanding:
Now there is no system to learn JS, just the recent temporary line of contact with functional programming.
So, to be continued 、、、
JavaScript functional programming-includes closures, chain optimization, and currying