Created
April 5, 2017 05:15
-
-
Save ronen-e/bdd2a0fbe6a61942dea25d908ac2be56 to your computer and use it in GitHub Desktop.
Create new scope in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function func() { | |
for (var i = 0; i < 10; i++) { | |
setTimeout(function() { | |
console.log('i:' + i); | |
}, 0); | |
} | |
} | |
// func(); | |
function solution1() { | |
for (let i = 0; i < 10; i++) { | |
setTimeout(function() { | |
console.log('i:' + i); | |
}, 0); | |
} | |
} | |
// solution1(); | |
function solution2() { | |
for (var i = 0; i < 10; i++) { | |
var fn = function(index){ console.log('i:' + index);}; | |
setTimeout(fn.bind(null, i), 0); | |
} | |
} | |
// solution2(); | |
function solution3() { | |
for (var i = 0; i < 10; i++) { | |
var fn = function(index){ console.log('i:' + index);}; | |
(function(index) { | |
setTimeout(() => {fn(index);}, 0); | |
})(i); | |
} | |
} | |
// solution3(); | |
function solution4() { | |
for (var i = 0; i < 10; i++) { | |
try { | |
throw i; | |
} catch(index) { | |
setTimeout(function() { | |
console.log('i:' + index); | |
}, 0); } | |
} | |
} | |
// solution4(); | |
function solution5() { | |
for (var i = 0; i < 10; i++) { | |
var fn = function(index){ console.log('i:' + index);}; | |
setTimeout(fn, 0, i); | |
} | |
} | |
// solution5(); | |
var solution6fn = function (index){ console.log('i:' + index);}; | |
function solution6() { | |
for (var i = 0; i < 10; i++) { | |
setTimeout("solution6fn(" + i + ")", 0); | |
} | |
} | |
//solution6(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment