js closures all in one
js closures all in one
setTimeout 闭包,log(i, arr[¡])
var, let, closures, IIFE
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-09-30
* @modified
*
* @description closures 闭包
* @difficulty Easy
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
* @best_solutions
*
*/
const log = console.log;
// setTimeout 闭包,log(i, arr[¡])
const arr = ["A", "B", "C"];
// var
for (var i = 0; i < arr.length; i++) {
if(i == 0) {
log(`var bug`);
}
setTimeout(() => {
log(`❌i =`, i, `arr[${i}] =`, arr[i]);
}, 1000);
}
// IIFE
for (var i = 0; i < arr.length; i++) {
((i) => {
setTimeout(() => {
if(i == 0) {
log(`\nIIFE`);
}
log(`🚀i =`, i, `arr[${i}] =`, arr[i]);
}, 1000);
})(i);
}
// closures
for (var i = 0; i < arr.length; i++) {
function test(i) {
setTimeout(() => {
if(i == 0) {
log(`\nclosures`);
}
log(`👍 i =`, i, `arr[${i}] =`, arr[i]);
}, 1000);
}
test(i);
}
// let
for (let i = 0; i < arr.length; i++) {
setTimeout(() => {
if(i == 0) {
log(`\nlet`);
}
log(`✅i =`, i, `arr[${i}] =`, arr[i]);
}, 1000);
}
/*
$ node closures.js
var bug
❌i = 3 arr[3] = undefined
❌i = 3 arr[3] = undefined
❌i = 3 arr[3] = undefined
IIFE
🚀i = 0 arr[0] = A
🚀i = 1 arr[1] = B
🚀i = 2 arr[2] = C
closures
👍 i = 0 arr[0] = A
👍 i = 1 arr[1] = B
👍 i = 2 arr[2] = C
let
✅i = 0 arr[0] = A
✅i = 1 arr[1] = B
✅i = 2 arr[2] = C
*/
for & log
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-10-16
* @modified
*
* @description for & log
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
* @best_solutions
*
*/
const log = console.log;
const len = 3;
for (var i = 0; i < len; i++) {
setTimeout(() => {
log(`❌ i =`, i);
}, 0);
}
// ES6 let
for (let j = 0; j < len; j++) {
setTimeout(() => {
if(j === 0) {
log(`\n`);
}
log(`✅ j =`, j);
// if(j === len - 1) {
// log(`\n`);
// }
}, 0);
}
// IIFE
for (var k = 0; k < len; k++) {
(function(k) {
setTimeout(() => {
if(k === 0) {
log(`\n`);
}
log(`✅ k =`, k);
}, 0);
})(k);
}
// 闭包 closure
for (var l = 0; l < len; l++) {
function test(l) {
setTimeout(() => {
if(l === 0) {
log(`\n`);
}
log(`✅ l =`, l);
}, 0);
}
test(l);
}
/*
$ node for-var-closures.js
❌ i = 3
❌ i = 3
❌ i = 3
✅ j = 0
✅ j = 1
✅ j = 2
✅ k = 0
✅ k = 1
✅ k = 2
✅ l = 0
✅ l = 1
✅ l = 2
*/
refs
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13757390.html
未经授权禁止转载,违者必究!