Home > Web Front-end > JS Tutorial > Basic use of JavaScript closure functions and solutions to problems encountered

Basic use of JavaScript closure functions and solutions to problems encountered

不言
Release: 2018-10-23 15:17:32
forward
2291 people have browsed it

This article brings you the basic use of JavaScript closure functions and solutions to problems encountered. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

I was always asked what a closure is during the interview. I didn’t really care about it before, let alone summarize it.

Closure is A function that can read the internal variables of other functions.
So, in essence, closure is a bridge connecting the inside of the function with the outside of the function.

(1) The most basic application of closure:

少废话,上代码

还是<<javascript高级程序设计>>的栗子,
Copy after login
Copy after login
function createComparisonFunction(propertyName) {
    return function(object1, object2) {
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];

        if(value1 < value2) {
            return -1;
        } else if(value1 > value2) {
            return 1;
        } else {
            return 0;
        }
    };
}
var compare = createComparisonFunction("name"); 

var result = compare({ name: "Nicholas" }, { name: "Greg" });
Copy after login
Copy after login

Analysis:
(1) The closure function can access its external function
The anonymous function returned is a Closure function, the active object in this anonymous function that accesses the external function is the propertyName parameter. Because the external scope chain is included by this anonymous function (it can also be understood as: the compare function contains the active object and global variable object of the
createComparisonFunction() function), the returned anonymous function can always access its external propertyName and global variables.
(2) The external variables referenced by the closure will not be destroyed due to the destruction of the scope in which they are located.
Because the active object of the external function is referenced in the returned closure function, the active object in createComparisonFunction() (i.e. propertyName) will not be destroyed after createComparisonFunction() is executed. Because although createComparisonFunction will destroy the scope chain in its execution environment after execution, its active object is still referenced by the closure function and placed in the scope of the execution environment of the anonymous function

( 2) Side effects of closure

(1). Closure can only obtain the last value of any variable in the function

        function createFunctions(){ 
            var result = new Array(); 
            for (var i=0; i < 10; i++){ 
                result[i] = function(){ 
                return i; 
                }; 
            } 
            return result; 
        }
        
        var res = createFunctions();
        console.log(res[0]());  //10
        console.log(res[1]());  //10
Copy after login
Copy after login

Principle:
Because of the scope chain of each function The active objects of the createFunctions() function are stored in them, so they all refer to the same variable i. When the createFunctions() function returns, the value of variable i is 10. At this time, each function refers to the same variable object that saves variable i, so the value of i inside each function is 10

Solution:

获取内部函数的对象result[i]时,使用匿名函数,并在匿名函数中再使用闭包函数,使得当前环境下的num被闭包函数函数调用,存储在作用域中不会被释放.
Copy after login
Copy after login
        function  createFunctions2(){
            var result  = new Array();
            for(var i = 0 ; i <10 ; i++){
                result[i] = (function(num){
                    return function(){
                        return num
                    }
                })(i)
            }
            return result;
        }
        
        var res2 =  createFunctions2();
        console.log(res2[0]());  // 0 
        console.log(res2[1]());  // 1
Copy after login
Copy after login

Principle:
Define an anonymous function and assign the result of the immediate execution of the anonymous function to the array. The anonymous function here has a parameter num, which is the value to be returned by the final function. When calling each anonymous function, we pass in the variable i. Since function parameters are passed by value, the current value of variable i is copied to parameter num. Inside this anonymous function, a closure accessing num is created and returned. This way, each function in the results array has its own copy of the num variable and can therefore return a different value.

(2). When an anonymous function is included outside the closure function, this points to the global

        var name = "The Window";
        var object = {
            name: "My Object",
            getNameFunc: function () {   
                return function () {        //匿名函数执行具有全局性
                    return this.name;       //this指向window
                };
            }
        };

        console.log(object.getNameFunc()())  //  The Window
Copy after login
Copy after login

Principle:
Each function will automatically obtain two special variables when it is called : this and arguments. When the internal function
searches these two variables, it will only search until its active object, so the external this cannot be obtained. At this time, getNameFunc() returns an anonymous function, and the anonymous function is global. Therefore this points to the global window

Solution:
Save the this object in the external scope in a variable that the closure can access, so that the closure can access the object

    var name2 =  "The  Window";
    var object2 = {
        name:"My Object",
        getNameFunc:function(){
            var that =  this; //将外部函数的this保存在外部函数的活动对象中(函数中申明的变量中)
            return function (){
                return that.name
            }
        }
    }
    
    console.log(object2.getNameFunc()())   //My Object
Copy after login
Copy after login

(3)
Disadvantages of closure
(1). Because a closure carries the scope of the function that contains it, it will occupy more memory than other functions. Excessive use of closures may lead to excessive memory usage
(2). Closures can only obtain the last value of any variable in the function, so pay attention to the writing








姧姧路                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     Posted 3 minutes ago                                                                                        Read 7 times                                                             It takes 12 minutes to read                                                                                                                            Basic use of JavaScript closure functions and solutions to problems encountered

  •                                                                                                                                                                                                                                                                                                                                                                                  

I was always asked what a closure was during the interview. I didn’t really care about it before, let alone summarize it.


A closure

is a function that can read the internal variables

of other functions.
So, in essence, closure is a bridge connecting the inside of the function with the outside of the function.

(1) The most basic application of closure:

少废话,上代码

还是<<javascript高级程序设计>>的栗子,
Copy after login
Copy after login
function createComparisonFunction(propertyName) {
    return function(object1, object2) {
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];

        if(value1 < value2) {
            return -1;
        } else if(value1 > value2) {
            return 1;
        } else {
            return 0;
        }
    };
}
var compare = createComparisonFunction("name"); 

var result = compare({ name: "Nicholas" }, { name: "Greg" });
Copy after login
Copy after login

Analysis:
(1) The closure function can access its external function
The anonymous function returned is a closure function , the active object in this anonymous function that accesses the external function is the propertyName parameter. Because the external scope chain is included by this anonymous function (it can also be understood as: the compare function contains the active object and global variable object of the
createComparisonFunction() function), the returned anonymous function can always access its external propertyName and global variables.
(2) The external variables referenced by the closure will not be destroyed due to the destruction of the scope in which they are located.
Because the active object of the external function is referenced in the returned closure function, the active object in createComparisonFunction() (i.e. propertyName) will not be destroyed after createComparisonFunction() is executed. Because although createComparisonFunction will destroy the scope chain in its execution environment after execution, its active object is still referenced by the closure function and placed in the scope of the execution environment of the anonymous function


(2) Side Effects of Closure

(1). Closure can only obtain the last value of any variable in the function

        function createFunctions(){ 
            var result = new Array(); 
            for (var i=0; i < 10; i++){ 
                result[i] = function(){ 
                return i; 
                }; 
            } 
            return result; 
        }
        
        var res = createFunctions();
        console.log(res[0]());  //10
        console.log(res[1]());  //10
Copy after login
Copy after login

Principle:
Because each function The active objects of the createFunctions() function are stored in the scope chain, so they all refer to the same variable i. When the createFunctions() function returns, the value of variable i is 10. At this time, each function refers to the same variable object that saves variable i, so the value of i inside each function is 10

Solution:

获取内部函数的对象result[i]时,使用匿名函数,并在匿名函数中再使用闭包函数,使得当前环境下的num被闭包函数函数调用,存储在作用域中不会被释放.
Copy after login
Copy after login
        function  createFunctions2(){
            var result  = new Array();
            for(var i = 0 ; i <10 ; i++){
                result[i] = (function(num){
                    return function(){
                        return num
                    }
                })(i)
            }
            return result;
        }
        
        var res2 =  createFunctions2();
        console.log(res2[0]());  // 0 
        console.log(res2[1]());  // 1
Copy after login
Copy after login

Principle:
Define an anonymous function and assign the result of the immediate execution of the anonymous function to the array. The anonymous function here has a parameter num, which is the value to be returned by the final function. When calling each anonymous function, we pass in the variable i. Since function parameters are passed by value, the current value of variable i is copied to parameter num. Inside this anonymous function, a closure accessing num is created and returned. This way, each function in the results array has its own copy of the num variable and can therefore return a different value.

(2). When an anonymous function is included outside the closure function, this points to the global

        var name = "The Window";
        var object = {
            name: "My Object",
            getNameFunc: function () {   
                return function () {        //匿名函数执行具有全局性
                    return this.name;       //this指向window
                };
            }
        };

        console.log(object.getNameFunc()())  //  The Window
Copy after login
Copy after login

Principle:
Each function will automatically obtain two special variables when it is called : this and arguments. When the internal function
searches these two variables, it will only search until its active object, so the external this cannot be obtained. At this time, getNameFunc() returns an anonymous function, and the anonymous function is global. Therefore this points to the global window

Solution:
Save the this object in the external scope in a variable that the closure can access, so that the closure can access the object

    var name2 =  "The  Window";
    var object2 = {
        name:"My Object",
        getNameFunc:function(){
            var that =  this; //将外部函数的this保存在外部函数的活动对象中(函数中申明的变量中)
            return function (){
                return that.name
            }
        }
    }
    
    console.log(object2.getNameFunc()())   //My Object
Copy after login
Copy after login

(3)
Disadvantages of closure
(1). Because a closure carries the scope of the function that contains it, it will occupy more memory than other functions. Excessive use of closures may lead to excessive memory usage
(2). Closures can only obtain the last value of any variable in the function, so pay attention to the writing


  • Basic use of JavaScript closure functions and solutions to problems encountered




#You may be interested





##Comment

                                                                                           Sort by time


Loading...


Show more comments


The above is the detailed content of Basic use of JavaScript closure functions and solutions to problems encountered. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template