Home > Web Front-end > JS Tutorial > body text

In one sentence: What is closure?

零下一度
Release: 2017-06-26 15:47:40
Original
2385 people have browsed it

In one sentence: a closure is a function that captures external bindings within the scope.

Official definition: An expression (usually a function) that has many variables and an environment bound to these variables, because these variables are also called part of the expression.

The relationship between free variables and closures: Free variables are closed to the creation of closures.

The internal logic is

Free variables: If there are other functions inside a function, then these internal functions can access the variables declared in the external function (these variables are called free variables).

Three characteristics of closures:

1. Function nested functions

2. Functions can refer to the outside inside Parameters and variables

3. Parameters and variables will not be recycled by the garbage collection mechanism

Disadvantages of closureIt is resident in memory and will Increase memory usage, improper use can easily cause memory leaks.

Benefits of closures:

1. I hope that a variable can Long-term resident in memory

2. Avoid pollution of global variables

3. Existence of private members

function fn(){ //Closure fn()
var a = 10;
function f1(){
a++;
console.log(a);
}
return f1;
}
var f = fn();
f();
f();
f();

闭包解决索引值问题:

 

 

 
 
 
  charset="UTF-8">
  <span class="html-tag">
 
 
 
 
  • 1
  •  
  • 2
  •  
  • 3
  •  
  • 4
  •  
     
     
     
     

    Memory leak problem:

    IE's JS objects and DOM objects use different garbage collection mechanisms, so closures will cause memory leaks in IE, that is, elements residing in memory cannot be destroyed. .

    ##var oDiv = document.getElementById("div1");//oDiv will remain in memory after use
    function closure(){
    ##oDiv.onclic = function(){
    alert("oDiv.innerHTML");//Using oDiv here will cause memory leaks
    };
    ##} closure();

    //Dereference oDiv to avoid memory leaks function closure(){ var oDiv = document.getElementById ("div1");//oDiv will remain in memory after use var test = oDiv.innerHTM oDiv.onclic = function(){ alert(test);//Using oDiv here will cause memory leaks }; oDiv = null ; }

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

    Related labels:
    source:php.cn
    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