Home >Web Front-end >JS Tutorial >javascript closure

javascript closure

巴扎黑
巴扎黑Original
2016-12-06 09:56:081135browse

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.

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