onclick 이벤트 스크립트를 함수로 재작성하고 웹페이지를 리로드 하고 버튼을 여러번 눌러 모드를 변경해보자. 여전히 버튼의 글자는 night일 것이다.
<script>
function nightDayHandler(self){
var target = document.querySelector('body');
if (self.value == 'night'){
target.style.backgroundColor='black';
self.value = 'day';
target.style.color='white';
var alist = document.querySelectorAll('a');
var i=0;
while(i<alist.length){ //반복문이 실행될 때마다 a태그를 하나하나 가져옴
alist[i].style.color='powderblue';
i=i+1;
}
}
else {
target.style.backgroundColor='white';
self.value = 'night';
target.style.color='black';
var alist = document.querySelectorAll('a');
var i=0;
while(i<alist.length){ //반복문이 실행될 때마다 a태그를 하나하나 가져옴
alist[i].style.color='blue';
i=i+1;
}
}
}
</script>
function nightDayHandler의 매개변수를 self로 하였고 함수 안의 this들을 모두 self로 바꾸어 주었다.
onclick이라는 이벤트 안에서 this는 이벤트가 소속된 태그를 가리키도록 약속되어 있는데 우리가 독립된 함수를 만들게 되면 this는 더 이상 input버튼이 아니고 전역객체를 가리키게 된다. (지금은 이해 못하는 이야기지만...)
그래서 this가 input을 가리키게 하기 위해서
<input type="button" value="night" onclick="
nightDayHandler(this);
">
nightDayHandler가 실행될 때 this값을 넘기도록 한다.
따라서 넘겨진 this값은 nightDayHandler가 실행될 때 넘겨지는 매개변수가 되고 그것을 self로 받는다.
그렇기 때문에 함수 안의 this를 모두 self로 변경한 것이다.
.
.
이 과정을 거치면 오류 없이 정상 동작하는 것을 볼 수 있다.
버튼을 1억개 만들어야 한대도 함수를 사용하면 모두 정상 동작하게끔 할 수 있으며, 수정도 한번에 할 수 있다.