Home  >  Article  >  Web Front-end  >  javascript closure

javascript closure

巴扎黑
巴扎黑Original
2016-12-10 09:16:231203browse

Concept:

A closure is a function that can read the internal variables of other functions.

Create a closure method:

Create another function inside a function, and access the local variables of this function through another function.

Js code

function box(){  
  var user ='Zhu';  
  return function(){  
    return user;  
  }  
}  
var b = box();  
console.log(b())  
console.log(box()())




Advantages of using closures:
Local variables can reside in memory to avoid global variable pollution.
Accumulate local variables through closures:

Js code

function func(){  
  var num=100;  
  incr=function(){// 未使用关键字var , 该函数为全局  
     num+=1;  
    return num;  
  }  
  var m1= function(){  
    console.log(num)  
  }  
  return m1;  
}  
  
var m1 = func();  
m1();//100  
console.log(incr())//101。。通过全局函数操作局部变量  
m1();//101





Disadvantages:
Since the local variable resources returned by the scope in the closure will not be destroyed and recycled immediately, it is easy to transition to using closures Resulting in performance degradation.


Statement:
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
Previous article:js closures and loopsNext article:js closures and loops