Based on the case

function createFn () {
    let name = 'ming';
}
createFn();
// When createFn is executed, the variable name will be released



function createFn () {
    let name = 'ming';
    return function() {
      	console.log(`my name is ${name}`); }}let getName = createFn(); Function returns a function and calls a member inside the original function
getName(); // my name is ming

// getName is an external function. When an external function has a reference to an internal member, the internal member name cannot be released. When we call getName, we access the name.

Copy the code

The concept of closures

Closures: A function is bundled with references to its surrounding state (lexical context) to form closures (closures allow you to access the scope of an outer function within an inner function)

  • You can call an inner function of a function from another scope and access members of that function scope

The core role of closures

Enlarges the scope of a function’s internal members

The nature of closures

Functions are placed on an execution stack during execution and removed from the stack when they are finished. However, scoped members on the heap cannot be freed because they are referenced externally, so the inner function can still access the members of the outer function.

  • A function is executed on the execution stack, then removed from the execution stack, freeing the memory of the internal member. However, after the function is removed, the memory of the internal member cannot be freed if there is an external reference.

The case of closures

Case a

The operation to calculate the square and cube of a numberMath.pow(4.2)
Math.pow(5.2)

// The second and third power is repeated many times, and now we have to write a second and third function
function makePower (power) {
  return function (number) {
    return Math.pow(number, power)
  }
}

/ / square
let power2 = makePower(2)
let power3 = makePower(3)

console.log(power2(5)) / / 25
console.log(power2(6)) / / 36
console.log(power3(5)) / / 125
Copy the code

Case 2

Calculate the salary of different levels of employees// Assume that the first function is passed the basic salary and the second parameter is passed the performance salary
// getSalary(12000, 2000)
// getSalary(15000, 3000)
// getSalary(15000, 4000)

// The base salary is the same at different levels, so we take the base salary out and then just add merit pay
function cretateSalary (base) { 
    return function (performance) { 
        return base + performance 
    }
}
let salaryLevel1 = cretateSalary(12000)
let salaryLevel2 = cretateSalary(15000)

console.log(salaryLevel1(2000)) / / 14000
console.log(salaryLevel2(3000)) / / 18000
console.log(salaryLevel2(4000)) / / 19000
Copy the code