Skip to content

Instantly share code, notes, and snippets.

@tnqsoft
Created September 5, 2017 04:29
Show Gist options
  • Save tnqsoft/f3dbc416017eb7478c6f71867de87832 to your computer and use it in GitHub Desktop.
Save tnqsoft/f3dbc416017eb7478c6f71867de87832 to your computer and use it in GitHub Desktop.
Javascript Study
<!doctype html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Javascript Study - Closure</title>
</head>
<body>
<h1>Test with normal</h1>
<button type="button" id="btn1">Click Item 1</button>
<button type="button" id="btn2">Click Item 2</button>
<button type="button" id="btn3">Click Item 3</button>
<button type="button" id="btn4">Click Item 4</button>
<button type="button" id="btn5">Click Item 5</button>
<h1>Test with Closure</h1>
<button type="button" id="btnClosure1">Click Item 1</button>
<button type="button" id="btnClosure2">Click Item 2</button>
<button type="button" id="btnClosure3">Click Item 3</button>
<button type="button" id="btnClosure4">Click Item 4</button>
<button type="button" id="btnClosure5">Click Item 5</button>
<script>
function test(x) {
console.log(x);
}
function buttonClick() {
for(var i = 1; i <= 5; i++) {
document.getElementById('btn'+i).addEventListener('click', function() {
test(i);
});
}
}
function testClosure(x) {
return function() {
console.log(x);
}
}
function buttonClosureClick() {
for(var i = 1; i <= 5; i++) {
document.getElementById('btnClosure'+i).addEventListener('click', testClosure(i));
}
}
buttonClick();
buttonClosureClick();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment