Created
March 14, 2019 00:43
-
-
Save gotoweb/e2c80a975cf830b7fe05ae3fbef856c0 to your computer and use it in GitHub Desktop.
callback in for loop: 클로저 및 bind 이용에 관한 문제에 대한 해답입니다. https://gist.github.com/gotoweb/e5d583fe28f0259fcd119c2d5355791f
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
| /* let keyword를 이용한 해결 */ | |
| var fns = []; | |
| for (let i=0; i<3; i++) { | |
| fns[i] = function() { | |
| console.log('My value:' + i); | |
| } | |
| } | |
| for (var j=0; j<3; j++) { | |
| fns[j](); | |
| } | |
| /* ------------------------------------ */ | |
| /* bind를 이용한 해답 */ | |
| var fns = []; | |
| for (var i=0; i<3; i++) { | |
| fns[i] = (function(j) { | |
| console.log('My value:' + j); | |
| }).bind(null, i); | |
| } | |
| for (var j=0; j<3; j++) { | |
| fns[j](); | |
| } | |
| /* ------------------------------------ */ | |
| /* 보너스: IIFE를 이용한 해답 */ | |
| var fns = []; | |
| for (var i=0; i<3; i++) { | |
| fns[i] = (function(j) { | |
| console.log('My value:' + j); | |
| })(i); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment