Programming way of thinking
- Object-oriented programming: Abstract things from the real world, through encapsulation, inheritance, polymorphism to demonstrate the relationship between things
- Procedure – oriented programming (functional programming) : The study of real – world thingscontactIt abstracts, it abstracts the operation
- Functional programming describes the mapping between data
- X -> f(relation, mapping) -> y=f(x)
- The same input must give the same output (pure function)
Functions are first-class citizens
- Functions can be assigned to variables
- Functions can be taken as arguments
- Functions can be returned as values
Higher-order functions
-
Function as a parameter
Iterating through the array, fn each element in the array;
Foreach is a higher-order function, which abstracts the general logic of traversing the part of the number group. The fn operation is entered as a parameter
function foreach(arr,fn){ for(let i=0; i<arr.length; i++){ fn(arr[i]); }} let arr = [1,2,3,4,5]; foreach(arr,function(i){ console.log(i); })Copy the code
-
Function as the return value
The following once is a higher-order function that controls logic that runs only once
function once(fn){ let done=false; return function(){ if(! done){ done = true; return fn.apply(fn,arguments); }}} let pay = once(function(money){console.log(' paid ${money} RMB '); }) // Only pay(5) once; pay(5); pay(5);Copy the code
What higher order functions do higher order functions are used to abstract the general part of the function, and abstraction helps us to screen out the details, so we focus on the target
closure
In another scope, call the inner function of a function, and access its internal variables through the inner function;
For example, calling function A returns function B, and using function B to access local variables of function A
The above pay function is also a closure because it accesses the done internal variable of the once function
function A() {
let s = "closure";
return function B() {
console.log(s);
}
}
let b = A();
b();
Copy the code
Variables in stack memory are typically garbage collected after the function finishes running, while variables in heap memory are not. The heap memory variable is garbage collected only when all references to it have been completed.
Therefore, the variables in the closure are not stored in stack memory, but in heap memory, which explains why the variables inside the closure function can still be accessed even if the place function is closed.
Closures extend the lifetime of local variables