코딩하는라민

생활코딩 Javascript #11 함수 활용 본문

Core/JavaScript

생활코딩 Javascript #11 함수 활용

코딩하는라민 2022. 10. 5. 10:00
728x90
반응형
BIG

Javascript #11 함수 활용

> 선행

 

 

28. 함수 활용


  
<input id="night_day" type="button" value="night" onclick="
function nightDayHandler(){
var target = document.querySelector('body');
if(this.value == 'night'){
target.style.backgroundColor = 'black';
target.style.color = 'white';
this.value = 'day';
var alist = document.querySelectorAll('a');
var i = 0;
while (i < alist.length){
alist[i].style.color = 'powderblue';
i = i + 1;
}
} else {
target.style.backgroundColor = 'white';
target.style.color = 'black';
this.value = 'night';
var alist = document.querySelectorAll('a');
var i = 0;
while (i < alist.length){
alist[i].style.color = 'blue';
i = i + 1;
}
}
}
">

- 위와 같이 input 안에 있던 함수를 script 태그에 따로 가져와 독립된 함수로 만들게 되면, this 라는 것이 '전역객체'를 가리키게 된다. 즉, 웹브라우저에서는 window 를 가리키게 된다.

 

 


  
<head>
...
<script>
function nightDayHandler(){
var target = document.querySelector('body');
if(this.value == 'night'){
target.style.backgroundColor = 'black';
target.style.color = 'white';
this.value = 'day';
var alist = document.querySelectorAll('a');
var i = 0;
while (i < alist.length){
alist[i].style.color = 'powderblue';
i = i + 1;
}
} else {
target.style.backgroundColor = 'white';
target.style.color = 'black';
this.value = 'night';
var alist = document.querySelectorAll('a');
var i = 0;
while (i < alist.length){
alist[i].style.color = 'blue';
i = i + 1;
}
}
}
</script>
</head>
<body>
<input id="night_day" type="button" value="night" onclick="
nightDayHandler();
">
</body>

- 따라서, 위와 같이 input 태그 안에 단순히 함수를 불러오게 된다면 함수가 제대로 실행되지 않는다.

 

 


  
<head>
...
<script>
function nightDayHandler(self){
var target = document.querySelector('body');
if(self.value == 'night'){
target.style.backgroundColor = 'black';
target.style.color = 'white';
self.value = 'day';
var alist = document.querySelectorAll('a');
var i = 0;
while (i < alist.length){
alist[i].style.color = 'powderblue';
i = i + 1;
}
} else {
target.style.backgroundColor = 'white';
target.style.color = 'black';
self.value = 'night';
var alist = document.querySelectorAll('a');
var i = 0;
while (i < alist.length){
alist[i].style.color = 'blue';
i = i + 1;
}
}
}
</script>
</head>
<body>
<input id="night_day" type="button" value="night" onclick="
nightDayHandler(this);
">
</body>

- input 안에 함수에 this 라는 매개변수를 넣고, 

- script 의 함수에 self 라는 매개변수를 넣고 모든 this 를 self 로 바꿔주면 함수가 정상적으로 실행되는 것을 확인할 수 있다.

결괏값 / 정상적으로 실행됨

 

 

 

 

728x90
반응형
BIG