Home  >  Article  >  Web Front-end  >  Simple application of JavaScript closure examples

Simple application of JavaScript closure examples

巴扎黑
巴扎黑Original
2017-09-02 13:50:281654browse

This article mainly introduces the simple application of JavaScript closures in detail, which has certain reference value. Interested friends can refer to

closure definition

In JavaScript, when an inner function is referenced by a variable outside its outer function, a closure is formed. Simply put, a closure is a function that can read the internal variables of other functions.

The role of closure:

1. You can read the variables inside the function
2. Keep the values ​​of these variables in memory. .
Simple application of closure

Example 1:


function a() { 
  var i = 0; 
 function b() {
  console.log(++i);
 } 
 return b;
}      
var c = a();  //执行完var c=a()后,变量c指向了函数b,再执行c()后就会显示i的值(为1)。
c();    //输出1

Example 2:


(function() { 
var i = 0; 
 return function(){
   console.log(++i);
  }
})()();     //输出1

Example three:


##

(function(i) { 
 return function(){
   console.log(++i);
  }
})(0)();     //输出1

Example four:


##

for (var i = 0; i < 3; i++) {
 setTimeout((function(i) {    
  return function() {
   console.log(i);
  };
 })(i), 2000);
 console.log(i+10);
}      //输出 10 11 12 (隔两秒后)0 1 2

Example 5:


for (var i = 0; i < 3; i++) {
 setTimeout((function(i) {
  return function() {
   console.log(i);
  };
 })(i)(), 2000);
 console.log(i+10);
}      //立即输出 0 10 1 11 2 12 ,(两秒后运行程序结束)

The above is the detailed content of Simple application of JavaScript closure examples. For more information, please follow other related articles on the PHP Chinese website!

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