익명함수(Anonymous function)
자바스크립트 익명 함수는 함수명 대신 변수명에 함수 코드를 저장하는 구현 방식이다. 익명 함수의 소스 코드는 변수값이므로 끝에 세미콜론 ';' 을 대입한다. 익명 함수는 호출 시 변수명을 함수명처럼 사용하면 된다.
<title>함수</title>
<script type="text/javascript">
//선언적 함수
function check(){
document.write('호출하면 동작함<br>');
}
//함수 호출
check();
//인자 앞에 var를 명시하면 오류 발생
function check2(msg){
document.write(msg + '을 좋아합니다.<br>');
}
//함수 호출
check2('가을');
function check3(num){
return num*num;
}
//함수 호출
var number = check3(10);
document.write('number = ' + number + '<br>');
//익명 함수
var play = function(){
document.write('운동을 좋아해요~~<br>');
};
//함수 호출
play();
var play2 = function(item){
document.write(item + '를 좋아해요<br>');
};
//함수 호출
play2('축구');
var play3 = function(x,y){
return x + y;
};
//함수 호출
var result = play3(5,8);
document.write('result = ' + result + '<br>');
//정의한 함수를 인라인 방식으로 호출하기
function checkIt(){
alert('인라인 방식으로 함수 호출하기');
}
</script>
</head>
<body>
<input type="button" value="확인" onclick="checkIt()">
</body>
</html>
<title>함수 사용시 주의사항</title>
</head>
<body>
<script type="text/javascript">
//함수의 이름이 같을 경우 마지막 함수 호출
function 함수(){
document.write('함수 A<br>');
}
function 함수(){
document.write('함수 B<br>');
}
//함수 호출
함수();
document.write('--------------<br>');
//함수 호출
함수2();//함수 호이스팅(=함수 선언전에 함수 호출하는 것)
function 함수2(){
document.write('함수2<br>');
}
document.write('--------------<br>');
//변수 선언은 중복될 수 있고 호출은 마지막 변수가 호출됨
//익명 함수를 대입하면 마지막 함수가 호출
var 함수3 = function(){
document.write('함수C<br>');
};
var 함수3 = function(){
document.write('함수D<br>');
};
//함수 호출
함수3();
document.write('--------------<br>');
//함수4();//오류 발생
//익명함수로 함수를 정의하면 함수 호이스팅이 발생하는 것이 아니라 변수 호이스팅이
//발생함. 익명함수 이전에 함수를 참조하면 undefined로 평가됨.
var 함수4 = function(){
document.write('함수4');
};
</script>
</body>
</html>
1. 지역변수(함수 레벨 스코프)
함수안에서 var를 사용해서 선언한 변수, 함수가 끝나면 소멸
2. 전역변수
함수밖에서 만들어진 모든 변수
함수안에서 var 없이 만들어진 변수
함수가 끝나도 메모리에 남아 있음
<title>지역변수와 전역변수</title>
</head>
<body>
<script type="text/javascript">
function test1(){
var i = 10;//지역변수
document.write(i + '<br>');
}
test1();
//지역변수는 함수가 종료되면 소멸되기 때문에 함수 밖에서 호출 불가능
//document.write(i + '<br>');
var j; //전역변수
function test2(){
j = 200;
document.write(j + '<br>');
}
test2();
function test3(){
document.write(j + '<br>');//전역변수
}
test3();
//전역변수
a = 100;
function test4(){
document.write(a + '<br>');
}
test4();
document.write('a = ' + a + '<br>');
//함수내에서 var를 명시하지 않고 변수를 선언하면 전역변수
function test5(){
m = 300;
document.write(m + '<br>');
}
test5();
function test6(){
document.write(m + '<br>');//전역변수
}
test6();
document.write('------------------<br>');
//주의
//함수 레벨 스코프에서는 제어문 블럭 안에 선언된 변수가 제어문을 벗어나도 소멸되지 않음
for(var i=0;i<=9;i++){//함수 밖에서 선언되어 전역변수로 인식
document.write(i + ' ');
}
document.write('<br>');
document.write(i);
</script>
</body>
</html>
<title>let</title>
</head>
<body>
<script type="text/javascript">
for(let i=1;i<=3;i++){ //블록 레벨 스코프
document.write(i + '<br>');
}
//document.write(i); //제어문 블록을 벗어나서 소멸됨
document.write('----------<br>');
let i = 10; //전역변수(함수 밖, 스크립트 안에만 있을 때)
document.write("전역변수 : " + i + '<br>');
function test2(){
let i = 20; //지역변수 우선(함수 안에서는)
document.write("지역변수 : " + i + '<br>');
}
//함수 호출
test2();
document.write(i); //전역변수
</script>
</body>
</html>
<title>const</title>
</head>
<body>
<script type="text/javascript">
const a = 10; //상수
document.write(a + '<br>');
document.write('------------<br>');
//a = 20; //상수는 변경 불가능
//document.wrtie(a + '<br>');
function test(){
const b = 20;
document.write(b + '<br>');
}
//함수 호출
test();
//const는 블록 레벨 스코프로 동작하기 때문에 함수를 벗어나면 소멸됨
//document.write(b);
</script>
</body>
</html>
<title>함수의 인자</title>
</head>
<body>
<script type="text/javascript">
function test(){
document.write('a = ' + a + '<br>');
document.write('b = ' + b + '<br>');
}
//함수 호출
test();
document.write('-------------<br>');
test(10);
document.write('-------------<br>');
test(10,20);
document.write('-------------<br>');
test(10,20,30);
</script>
</body>
</html>
[가변인자 함수]
- 가변인자 함수는 매개 변수를 선언된 형태와 다르게 사용했을 때도 매개 변수를 모두 활용하는 함수이다.
- 자바스크립트의 모든 함수는 내부에 자동으로 변수 arguments를 갖는다.
- 변수 arguments는 매개 변수의 배열이다.
<title>가변인자 함수</title>
</head>
<body>
<script type="text/javascript">
function test(){
for (let i=0;i<arguments.length;i++){
document.write('arguments['+i+']:' + arguments[i] + '<br>');
}
}
//함수 호출
test(10);
document.write('----------<br>');
test(10,20);
document.write('----------<br>');
test(10,'자동차');
</script>
</body>
</html>
<title>return</title>
</head>
<body>
<script type="text/javascript">
function returnTest(){
document.write('문장A<br>');
for(let i=1;i<=10;i++){
//조건문
if(i == 5){
//break; //i가 5이면 반복을 중지하고 for문을 빠져나감
return; //i가 5이면 반복을 중지하고 함수를 빠져나감
}
document.write(i + '<br>');
}
document.write('문장B<br>');
}
//함수 호출
returnTest();
document.write('프로그램 끝!!');
</script>
</body>
</html>
1)
[실습]
두 수를 입력해서 덧셈, 곱셈, 뺄셈, 나눗셈을 해서 결과 값을 출력하시오.
덧셈(add), 곱셈(multi), 뺄셈(sub), 나눗셈(div)을 수행하는 함수를
만들어서 결과 값을 구하시오.
[입력 예시] prompt 사용 - 첫번째 숫자, 두번째 숫자 입력
[출력 예시]
덧셈 : 10
뺄셈 : 2
곱셈 : 24
나눗셈 : 1.5
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>실습</title>
</head>
<body>
<script type="text/javascript">
function add(num1, num2){
return num1 + num2;
}
function sub(num1,num2){
return num1 - num2;
}
function multi(num1,num2){
return num1 * num2;
}
function div(num1,num2){
return num1 / num2;
}
var first = prompt('첫번째 숫자','');
var second = prompt('두번째 숫자','');
//왜 더할때만 Number?
document.write('덧셈 : ' + add(Number(first), Number(second)) + '<br>');
document.write('뺄셈 : ' + sub(first, second) + '<br>');
document.write('곱셈 : ' + multi(first, second) + '<br>');
document.write('나눗셈 : ' + div(first, second) + '<br>');
</script>
</body>
</html>
2)
[실습]
키와 몸무게를 입력해서 적정 몸무게를 구하는 함수(avgWeight)를 만들어보자.
함수에 키와 몸무게를 전달하면 다음 예와 같이 출력되게 작성해 보자
적정 몸무게 공식 : (height-100)*0.9
[입력 예시] prompt - 키, 몸무게 입력
[출력 예시]
당신의 키는 180cm이고 현재 몸무게는 90kg이며 적정 몸무게는 72kg입니다.
적정 몸무게 초과(or 적정 몸무게 or 적정 몸무게 미만)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>실습</title>
</head>
<body>
<script type="text/javascript">
function avgWeight(height, weight){
//적정 몸무게
let avg_weight = (height - 100) * 0.9;
document.write('당신의 키는 ' + height + 'cm이고 ');
document.write('현재 몸무게는 ' + weight + 'kg이며 ');
document.write('적정 몸무게는 ' + avg_weight + 'kg입니다.<br>');
if(weight > avg_weight){
document.write('적정 몸무게 초과');
}else if(weight == avg_weight){
document.write('적정 몸무게');
}else{
document.write('적정 몸무게 미만');
}
}
//왜 let쓰는지
let height = prompt('키 입력','');
let weight = prompt('몸무게 입력','');
avgWeight(height,weight);
</script>
</body>
</html>