Table of Contents
What is a closure:
Home Web Front-end JS Tutorial What is closure

What is closure

Sep 08, 2017 pm 01:12 PM
What Closure

What is a closure:

A closure refers to a function that has access to a variable in the scope of another function.
–《Javascript Advanced Programming》

在这个函数fun2中可以访问另一个函数中的变量a,所以fun2()就是一个闭包。
function fun1 () { 
      var  a = 0; 
      function fun2 () {  
          console.log(a);  
      } 
      fun2(); }
Copy after login

1. Call the closure method outside the defined function, escape method:

  (1). The function is assigned to a global variable;

var globalVar; function outer() { 
      console.log(‘outer’); 
      function inner(){ 
          console.log(‘inner’); 
      } 
      globalVar = inner;       
      } outer(); // outer 
      globalVar(); // inner;
Copy after login

In this example inner() successfully escapes through the reference of the global variable, and can now be called globally, and can refer to the variable of outer()

  (2). 'Rescue' the reference of the inner function by returning the value

function outer() { 
      console.log(‘outer’); 
      function inner(){ 
          console.log(‘inner’); 
      }    
      return inner;       
      } 
      var fn = outer(); // outer 
      fn(); // inner;
Copy after login

In this example inner() escapes successfully by returning the value, and now it can be Called globally, and can refer to variables of outer()

2. The impact of calling closures outside the function: increased memory usage;

Under normal circumstances, the function is after the function call ends The execution environment leaves the environment stack, the defined variables are discarded (disposal is related to the garbage collection mechanism), the active variables (variable objects) will be destroyed, and the memory will be released. But now because the scope chain of the closure includes the variable object of the external function, the variables of the external function may be referenced again. The garbage collection mechanism will not discard the variables of the external function, and the variable objects of the external function are retained in the memory. This increases the memory usage.

3. The relationship between closures and variables: Common misunderstandings and solving techniques in closures

Closures save the entire variable object containing the function, and the external object variables obtained are closure The object variable at the time the package is called is usually the last value of the external function variable.

Example:

function createFun() { 
      var result = []; 
      for ( var i = 0; i < 10; i++) { 
          result[i] = function() { 
              return i; 
          }; 
      } 
      return result; } var result = createFun(); console.log(result5); // 10
Copy after login

The return value of the external function here is an array, and the array values ​​are references to different functions (closures). We will mistakenly think that each closure The return values ​​of the package calls are different, but in fact each function returns the same value. Because when the closure is called, the external function that called the closure has been executed. At this time, i = 10 in the variable object of the external function, and the return value of our closure is i, the closure will obtain the external variable object at the time of the call. , i at this time is 10.

Solution:

function createFun() { 
      var result = []; 
      for ( var i = 0; i < 10; i++) { 
          result[i] = function(num) { 
              return function() { 
                     return num; 
              }; 
           }(i); 
      } 
      return result; } var result = createFun(); console.log(result5); // 5
Copy after login

In the loop, we define an anonymous array and assign the result of immediately executing the anonymous function to the array. The anonymous function here is A parameter num, each time i is passed as a parameter to num, each time num is looped, a different value will be obtained, so a different function is returned each time (the difference is that the num value is different), when the array value is called externally, it will be returned Different values, as expected.

4. Pay attention to the this value in the closure

First of all, regarding the this point in the function, we should know that this points to the object that calls the function. If there is no explicit calling object, it points to the window object.

It is easy to mistake the this point in the closure, for example:

var name = “window”; 
      var o = { 
          name: “object”, 
          getName: function() { 
              return function() { 
                  return this.name; 
              }; 
          } 
      }; console.log(o.getName()()); // window
Copy after login

It can be seen that the closure this points to the global object. After analysis, you can put o.getName ()() is written as (o.getName())(). This expression is equivalent to executing o.getName() in the first step. This function returns an anonymous function (closure) and then executes it globally. This closure is not called through object o, so this points to the global object.

5. The problem of memory leaks, how to reduce unnecessary memory usage

function assignHandler() { 
          var ele = documnet.getElementById(“somenode”); 
          ele.onclick = function() { 
              console.log(ele.id); 
          }; 
          }
Copy after login

In the above example, the method of defining ele is related to the anonymous function, so ele is saved has a reference to the anonymous function, and the closure will reference the containing function and also reference the ele object, which will cause a circular reference to the object. The ele element (the DOM element takes up a large amount of memory) will always be saved in the memory and cannot be released. The solution The method is as follows:

function assignHandler() { 
          var ele = documnet.getElementById(“somenode”); 
          var id = ele.id; 
          ele.onclick = function() { 
              console.log(id);    // 通过id值中介表面上解除了与ele的循环引用 
          }; 
          ele = null; // 手动解除引用 }
Copy after login

The above is the detailed content of What is closure. For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
What is the meaning of closure in C++ lambda expression? What is the meaning of closure in C++ lambda expression? Apr 17, 2024 pm 06:15 PM

In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

What are the advantages and disadvantages of closures in C++ functions? What are the advantages and disadvantages of closures in C++ functions? Apr 25, 2024 pm 01:33 PM

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

How to implement closure in C++ Lambda expression? How to implement closure in C++ Lambda expression? Jun 01, 2024 pm 05:50 PM

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

Solve the memory leak problem caused by closures Solve the memory leak problem caused by closures Feb 18, 2024 pm 03:20 PM

Title: Memory leaks caused by closures and solutions Introduction: Closures are a very common concept in JavaScript, which allow internal functions to access variables of external functions. However, closures can cause memory leaks if used incorrectly. This article will explore the memory leak problem caused by closures and provide solutions and specific code examples. 1. Memory leaks caused by closures The characteristic of closures is that internal functions can access variables of external functions, which means that variables referenced in closures will not be garbage collected. If used improperly,

What is the function of cortana? What is the function of cortana? Jan 15, 2024 pm 10:15 PM

In the process of using the Windows 10 operating system developed by Microsoft, many users are curious and confused about the new technology called Cortana. Cortana's official name in the Chinese context is "Cortana", which is actually a built-in function of the Windows 10 system. Cortana, an artificial intelligence (AIassistant) service program. Frequently asked questions and solutions. How to open Cortana and not respond. Solution steps. Chinese solution is not supported. How to put the search box into Cortana. What software is Cortana? Answer: "Cortana" It is a cloud platform personal intelligent assistant carefully built by Microsoft. It has two usage modes: login and non-login. When you are logged in

The role of golang function closure in testing The role of golang function closure in testing Apr 24, 2024 am 08:54 AM

Go language function closures play a vital role in unit testing: Capturing values: Closures can access variables in the outer scope, allowing test parameters to be captured and reused in nested functions. Simplify test code: By capturing values, closures simplify test code by eliminating the need to repeatedly set parameters for each loop. Improve readability: Use closures to organize test logic, making test code clearer and easier to read.

The impact of function pointers and closures on Golang performance The impact of function pointers and closures on Golang performance Apr 15, 2024 am 10:36 AM

The impact of function pointers and closures on Go performance is as follows: Function pointers: Slightly slower than direct calls, but improves readability and reusability. Closures: Typically slower, but encapsulate data and behavior. Practical case: Function pointers can optimize sorting algorithms, and closures can create event handlers, but they will bring performance losses.

Chained calls and closures of PHP functions Chained calls and closures of PHP functions Apr 13, 2024 am 11:18 AM

Yes, code simplicity and readability can be optimized through chained calls and closures: chained calls link function calls into a fluent interface. Closures create reusable blocks of code and access variables outside functions.

See all articles