Lexical Scope
function init() {
var name = "yeoUl";
function displayName() {
console.log(name);
}
displayName();
}
init();
Closure
function makeFunc() {
var name = "yeoUl";
function displayName() {
console.log(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
function makeAdder(x) {
var y = 1;
return function(z) {
y = 100;
return x + y + z;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2));
console.log(add10(2));
Closure의 Scope
var e = 10;
function sum(a){
return function(b){
return function(c){
return function(d){
return a + b + c + d + e;
}
}
}
}
console.log(sum(1)(2)(3)(4));
Closure 대표적 사용 오류
<!DOCTYPE html>
<html>
<body>
<p id="help">Helpful notes will appear here</p>
<p>E-mail: <input type="text" id="email" name="email"></p>
<p>Name: <input type="text" id="name" name="name"></p>
<p>Age: <input type="text" id="age" name="age"></p>
<script type="text/javascript" src="./normal_mistake.js"></script>
</body>
</html>
function showHelp(help) {
document.getElementById('help').innerHTML = help;
}
function setupHelp() {
var helpText = [
{'id': 'email', 'help': '이메일'},
{'id': 'name', 'help': '이름'},
{'id': 'age', 'help': '나이'}
];
for (var i = 0; i < helpText.length; i++) {
var item = helpText[i];
document.getElementById(item.id).onfocus = function() {
showHelp(item.help);
}
}
}
setupHelp();
해결된 버전 1
function showHelp(help) {
document.getElementById('help').innerHTML = help;
}
function setupHelp() {
var helpText = [
{'id': 'email', 'help': '이메일'},
{'id': 'name', 'help': '이름'},
{'id': 'age', 'help': '나이'}
];
for (var i = 0; i < helpText.length; i++) {
let item = helpText[i];
document.getElementById(item.id).onfocus = function() {
showHelp(item.help);
}
}
}
setupHelp();
해결된 버전 2
function showHelp(help) {
document.getElementById('help').innerHTML = help;
}
function setupHelp() {
var helpText = [
{'id': 'email', 'help': '이메일'},
{'id': 'name', 'help': '이름'},
{'id': 'age', 'help': '나이'}
];
helpText.forEach(function(text) {
document.getElementById(text.id).onfocus = function() {
showHelp(text.help);
}
})
}
setupHelp();