欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

闭包中变量值的改变(代码实例)

程序员文章站 2022-07-08 14:09:16
1.对于闭包中的变量是怎么回事? function makeCounter() { var i = 0; console.log(i); ret...

1.对于闭包中的变量是怎么回事?

function makeCounter() {
    var i = 0;
    console.log(i);
    return function(){
        console.log(++i);
        console.log(i);
    };   
}

//记住:`counter`和`counter2`都有他们自己的变量 `i`

var counter = makeCounter();
counter();//1
counter();//2

makeCounter();

var counter2 = makeCounter();
counter2();//1
counter2();//2

2.异步执行的顺序是怎样的?

for (var i = 0; i < 5; ++i) {
  setTimeout(function () {
    console.log(i + ' ');
  }, 100);
}

for (var j = 5; j < 10; ++j) {
  setTimeout((function (num) {
    console.log(num + ' ');
  })(j), 100);
}

for (var k = 10; k < 15; k++) {
	
	(function(num){
		setTimeout(function () {
    		console.log(num + ' ');
  		}, 100);

	})(k);	
}

for (var n = 15; n < 20; n++) {
	
	add(n);
}

function add(num){
	setTimeout(function(){
		console.log(num);
	});

输出的结果是 5,6,7,8,9,15,16,17,18,19,5,5,5,5,5,10,11,12,13,14