Home > Article > Web Front-end > javascript closure
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.