• Nested function

  • An inner function references data from an outer function

/ / sample
for (var i = 1; i <= 10; i++) {
	setTimeout(function () {
		console.log(i)
	}, 1000)}// 11, 11, 11, 11, 11, 11, 11, 11

for (var i = 1; i <= 10; i++) {
	(function (j) {
		setTimeout(function () {
			console.log(j)
		}, 1000)
	})(i)
} 
// 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

for (let i = 1; i <= 10; i++) {
	setTimeout(function () {
		console.log(i)
	}, 1000)}// 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Copy the code