Home > Web Front-end > JS Tutorial > body text

Simple application of JavaScript closure examples

巴扎黑
Release: 2017-09-02 13:50:28
Original
1597 people have browsed it

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
Copy after login

Example 2:


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

Example three:


##

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

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
Copy after login

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 ,(两秒后运行程序结束)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!