search
HomeWeb Front-endJS TutorialBasic use of JavaScript closure functions and solutions to problems encountered

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:

少废话,上代码

还是>的栗子,
function createComparisonFunction(propertyName) {
    return function(object1, object2) {
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];

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

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

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 <p>Principle:<br>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</p><p> Solution: </p><pre class="brush:php;toolbar:false">获取内部函数的对象result[i]时,使用匿名函数,并在匿名函数中再使用闭包函数,使得当前环境下的num被闭包函数函数调用,存储在作用域中不会被释放.
        function  createFunctions2(){
            var result  = new Array();
            for(var i = 0 ; i <p>Principle: <br>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. </p><p>(2). When an anonymous function is included outside the closure function, this points to the global </p><pre class="brush:php;toolbar:false">        var name = "The Window";
        var object = {
            name: "My Object",
            getNameFunc: function () {   
                return function () {        //匿名函数执行具有全局性
                    return this.name;       //this指向window
                };
            }
        };

        console.log(object.getNameFunc()())  //  The Window

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

(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:

少废话,上代码

还是>的栗子,
function createComparisonFunction(propertyName) {
    return function(object1, object2) {
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];

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

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

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 <p>Principle:<br>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</p><p> Solution: </p><pre class="brush:php;toolbar:false">获取内部函数的对象result[i]时,使用匿名函数,并在匿名函数中再使用闭包函数,使得当前环境下的num被闭包函数函数调用,存储在作用域中不会被释放.
        function  createFunctions2(){
            var result  = new Array();
            for(var i = 0 ; i <p>Principle: <br>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. </p><p>(2). When an anonymous function is included outside the closure function, this points to the global </p><pre class="brush:php;toolbar:false">        var name = "The Window";
        var object = {
            name: "My Object",
            getNameFunc: function () {   
                return function () {        //匿名函数执行具有全局性
                    return this.name;       //this指向window
                };
            }
        };

        console.log(object.getNameFunc()())  //  The Window

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

(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!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment