Function은 왜 필요할까?
정말 기본적인 방법으로 필요성을 알아보자
우선 아래와 같은 리스트를 만든다고 가정해보자.
해당 리스트를 만들기 위해 html을 활용한다면 코드는 아래와 같다
<ul>
<li>1</li>
<li>2-1</li>
<li>2-2</li>
<li>3</li>
<li>2-1</li>
<li>2-2</li>
</ul>
그렇다면 일일이 손으로 치기도 버겁고, 반복문을 쓰자니 중간에
불청객 '3'이 끼여있다.
이럴때 function을 사용하면 비교적 쉽게 풀어낼 수 있다.
코드는 아래와 같다.
<ul>
<script>
function list(){
document.write('<li>2-1</li>');
document.write('<li>2-2</li>');
}
document.write('<li>1</li>');
list();
document.write('<li>3</li>')
list();
</script>
</ul>
이 둘의 결과값은 똑같지만, 로직은 전혀 다르다. 만약 1억개를 수정해야할 경우, 매번 손으로 1억번 수정해야하는 html과 다르게 java에선 function을 활용해 시간을 비약적으로 줄일 수 있다.
fucntion name (){로직}
name();을 사용한다면 함수가 적용되는 메커니즘
시스템에서 name을 읽고 괄호와 ;가 찍혔을때, "아! 함수를 시행해야겠다"며 작동되는 방식
parameter와 argument는 무엇일까?
parameter = 매개변수
argument = 전달인자
parameter (매개변수)
함수의 정의 부분에 나열되어 있는 변수, 여기서는 plus 함수 정의시에 사용되는 a, b를 parameter(매개변수) 라고 한다.
function plus(a, b):
return a + b
argument (전달인자)
함수를 호출할때 전달 되는 실제 값, 여기서는 plus 라는 함수에 넣어주는 값 1, 2를 argument(전달인자)라고 한다.
result = plus(1, 2)
직관적으로 풀어보자면 다음 a 함수 정의를 참고하자.
<script>
function a(left, right){
document.write(left+right);
}
a(4,3);
a(2,7);
</script>
parameter = left, right
argument = (4,3) (2,7)
즉,
parameter는 함수 정의 부분에 나열되어 있는 변수를 뜻한다
argument는 실질적으로 함수에 투입되는 값을 뜻한다.
이 둘을 function과 접목시켰을때, 식을 통해서 argument에 따라 다른 값을 만들수도 있다.
<script>
function plus(){
document.write(1+1+'<br>');
}
plus ();
function sum(left, right){
document.write(left+right+'<br>');
}
function sumcolor(left, right){
document.write('<div style="color:blue">'+left+right+'</div>');
}
sum(2,3); // 5
sumcolor(3,3);
sum(3,4); // 7
</script>
위 사진과 같은 값이 나온다.
plus라는 이름의 함수에 document.write(1+1)라 정해둬서
plus();를 입력하면 고정된 값 '2'만 나오게 된다
5, 33, 7이 나왔다. 다만 33이 왜 숫자가 안더해지고 붙어버리는 건지에 대한 공부는 더 필요할 듯하다. 혹시라도 알고 있다면 도와주세요 ㅠ
마지막은 산출이다.
버튼을 눌렀으면 결과값이 나와야한다.
return이 그 역할을 해준다
return을 이해하기가 가장 어려웠다. 돌려준다고? 값을? 왜?
MDN의 설명에 따르면 return은 함수 실행을 종료하고 호출지점으로 반환합니다 라고 기재돼있다.
즉, function에서 escape할 수 있다는 뜻이다.
<script>
function sum2(left, right){
return left+right;
}
document.write(sum2(2,3)+'<br>');
document.write('<div style = "color:red">'+sum2(2,3)+'</div>');
document.write('<div style = "font-size:3rem;">'+sum2(2,3)+'<div>');
</script>
해당 식을 사용하면 이렇게 나오는 것을 볼때
return 을 활용하면 argument에 있는 값을 각각 처리하며 다음 단계로 넘어가는 것을 볼 수 있다.
이전에 만들어둔 다크모드 버튼을 스크립트로 활용해 처리할 수 있다.
수십만개의 버튼을 함수 처리해버린다면, 일일이 손으로 뜯어고칠 필요 없이
함수만 수정해주면 된다.
<input id="night_day"type="button" value="night" onclick="
var target = document.querySelector('body');
if(this.value === 'night') {
target.style.backgroundColor='black';
target.style.color='white';
this.value = 'day';
} else {
target.style.backgroundColor='white';
target.style.color='black';
this.value = 'night';
}
">
현재 해당 코드는 각각의 버튼에 기능이 할당돼있기 때문에, 고치는 수도 버튼 수에 따라 다르다.
이 버튼을 함수 처리한다면 수 십만개가 되더라도 걱정이 없다.
다음과 같다.
<script>
function buttonhandler(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 = 'skyblue';
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 = 'green';
i = i + 1;
}
}
}
</script>
</head>
<body>
<h1><a href="index.html">NEW WEB</a></h1>
<input type="button" value="night" onclick="
buttonhandler(this);
">
버튼 핸들러라는 함수를 넣어주고, 해당 parameter로 self를 넣어준다.
그리고 input의 onclick 값엔 함수 이름인 버튼 핸들러를 넣고, argument로 this 를 넣어준다면 정상 작동한다.
외양상 차이는 없지만, 로직상 묶였다고 볼 수 있다.