当前位置:网站首页>Understanding of closures

Understanding of closures

2022-06-26 07:54:00 Forge ahead and have a bright future

        What is a closure ? Usually implemented in nested functions , It refers to variables in the scope of a function that refer to other functions . It is used to enable external function methods to get the variables inside the function . It is a bridge linking the function inside and outside .

        The benefits of closures :1、 Keep variables in memory all the time   2、 So that the external can get the internal variables of the function ;

function f1(){
   var n = 1;
   return function(){
     console.log(n);
     n += 1;
   }
}

var f2 = f1() 
f2() //1
f2() //2

     return Anonymous function of is defined by global variable f2 quote , This anonymous function will not be destroyed , therefore n It will not be destroyed .

      What to pay attention to : Unnecessary use of closures can lead to excessive memory consumption , Even lead to memory leaks .

Reference resources : Study Javascript Closure (Closure) - Ruan Yifeng's Weblog

原网站

版权声明
本文为[Forge ahead and have a bright future]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170607493187.html