JavaScript closure detailed explanation and case

JavaScript closure detailed explanation and case

1. Variable scope

  1. Global variables can be used inside the function
  2. Local variables cannot be used outside the function
  3. When the function is executed, the local variables in this scope will be destroyed

2. Closure

  1. Closure: A function that has access to a variable in the scope of another function (the function where the variable is located is the closure function, and the closure is a typical higher-order function)
  2. The role of closures: extend the scope of the variable
//方法一
function fn() {
            var num = 10;
            return function() {
                console.log(num);
            }
}
var f = fn();
f();  //10
//方法二
function fn() {
            var num = 10;
            function fn1() {
                console.log(num);
            }
            return fn1();
}
fn();  //10

Three. Case

  1. Case 1: Clicking on each dish will print out the corresponding index number
<body>
    <ul class="nav">
        <li>红烧茄子</li>
        <li>凉拌海带丝</li>
        <li>泡椒风爪</li>
        <li>韩式烤肉</li>
    </ul>
    <script>
        //点击每一道菜会打印出索引号
        //方法1.利用动态添加属性的方法(传统方法)
        var lis = document.querySelectorAll('li');
        for (var i = 0; i < lis.length; i++) {
            lis[i].index = i;
            lis[i].onclick = function() {
                alert(this.index);
            }
        }
        //方法2.利用闭包的方法
        for (var i = 0; i < lis.length; i++) {
            (function(i) {
                lis[i].onclick = function() {
                    console.log(i);

                }
            })(i); //立即执行函数最后一个小括号用来传递参数,第一个小括号用来接收参数
        }
    </script>
</body>
  1. Case 2: Print the content of all li elements after 3 seconds
<body>
    <ul class="nav">
        <li>红烧茄子</li>
        <li>凉拌海带丝</li>
        <li>泡椒风爪</li>
        <li>韩式烤肉</li>
    </ul>
    <script>
        //3秒钟之后打印所有li元素的内容
        var lis = document.querySelectorAll('li');
        for (var i = 0; i < lis.length; i++) {
            (function(i) {
                setTimeout(function() {
                    console.log(lis[i].innerHTML);

                }, 3000)

            })(i);
        }
    </script>
</body>
  1. Case 3: Calculating the taxi price (the starting price of a taxi within 3 kilometers is 13, and the additional one kilometer is more than 5 yuan, the user can enter the number of kilometers to calculate the taxi price, if there is congestion, the total price will be 10 yuan more)
var car = (function() {
        var start = 13;
        var total = 0;
        return {
                price: function(n) {
                    if (n <= 3) {
                        total = start;
                    } else {
                        total = (n - 3) * 5 + start;
                    }
                    return total;
                },
                jam: function(n) {
                    if (n = 0) {
                        return total = total;
                    } else {
                        return total = total + 10;
                    }
                }
      };
})();
car.price(5);
var money = car.jam(1);
console.log(money);

Four. Thinking

  1. The return value of the following code
var name = 'The Window';
        var object = {
            name: "My Object",
            getNameFunc: function() {
                that = this;
                return function() {
                    return that.name;
                };
            }
        };
console.log(object.getNameFunc()());  //My Object
  1. The return value of the following code
var name = 'The Window';
        var object = {
            name: "My Object",
            getNameFunc: function() {
                return function() {
                    return this.name;
                };
            }
        };
console.log(object.getNameFunc()());  //The Window

Did you get it right?

Guess you like

Origin blog.csdn.net/Angela_Connie/article/details/110312153