What is closure of function

  1. what is closure

(1). Closure: Lexical representation of a function that includes variables that do not need to be calculated, that is, the function can use variables defined outside the function
(2). Usage: A method that both reuses a variable and protects the variable from tampering Programming method

  1. Why use closures

(1). Global variables: Advantage: can be reused, disadvantage: can be easily contaminated anywhere
(2). Local variables: Advantage: can only be used within the function and will not be polluted, disadvantage: cannot be reused!

  1. When to use

If you want a function to reuse a variable and protect the variable from being tampered with, use a closure!

  1. How to use 3 steps

(1). Define an outer function to wrap the inner function and the variables to be protected.
Problem: The inner function becomes a local function within the outer function and cannot be used externally!
(2). The outer function returns the inner function to the outside!
Note: Do not name the inner function! Because anyway, after the inner function is received externally, people will give new variable names.
Question: Only when the function is called can the return result be obtained.
If the function is not called, it will not be executed and the return result will not be obtained!
(3). People who want to use the inner function must call the outer function to obtain the inner function! to use!

  1. Summarize

(1). What exactly is a closure: The scope object of the outer function is called a closure object because it is referenced and protected by the inner function.
(2). Question: The reason for the formation of closure: After the outer function is called, because the inner function refers to the scope object of the outer function, the scope object of the outer function cannot be released, forming a closure!

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>闭包</title>
</head>
<body>
    <script>
        var 函数=function(){
     
     
            // 声明类全局变量=身上1000元零钱
            var 零钱=1000;
            return function(消费){
     
     
                零钱-=消费;
                document.write(`还剩${
       
       零钱}元<br>`);
            };
        };
        var 剩余=函数();
        剩余(100);
        剩余(100);
        剩余(100);
    </script>
</body>
</html>

Guess you like

Origin blog.csdn.net/u010100877/article/details/109488506