Home >Web Front-end >JS Tutorial >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.
function box(){ var user ='Zhu'; return function(){ return user; } } var b = box(); console.log(b()) console.log(box()())
Advantages of using closures:
You can store local variables in memory to avoid global variable pollution.
Accumulate local variables through closures:
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, excessive use of closures can easily lead to performance degradation.