본문 바로가기

학원/javascript-학원

함수

728x90

 

기본 함수 정의문

 

일반 함수 정의 / 익명 함수 선언 참조

 

<예제 - 일반함수>

 

- hello1 출력

 

<예제>

 

- 호이스팅으로 출력됨

- 아래의 주석을 풀면 hello1, hello2 두개가 만들어짐 

- 호이스팅 개념으로 함수를 2번 호출했기 때문

 

<예제 - 익명함수>

 

- bye3출력

- 호이스팅 개념을 적용시키려 하면 오류가 나서 출력되지 않음

- 호이스팅은 일반 함수에만 적용

 

<예제>

 

매개변수가 있는 함수 정의문

 

매개변수 없이 함수에 전달된 값 받아오기

 

<예제>

 

 

<예제>

 

- 일반함수, 매개함수, 호이스팅 사용

 

return문

 

 

<예제>

 

 

<예제>

 

 

재귀함수 호출

 

- 자기 자신을 호출

 

<예제>

    <script>
        var num = 0;

        function testFnc() {
            num++;
            document.write(num,"<br>");
            if(num==10) return;

            testFnc();
        }
        testFnc();
    </script>
 

함수 스코프

 

전역, 지역

 

<예제>

 

 

<예제 - 익명함수>

 

 

객체 생성자 함수

 

- function이 위에서 만든 객체 생성자 함수가 됨

- 함수 안의 필드, 메소드 값을 사용하는 것

 

<예제>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        function checkWeight(name, height, weight) {
            this.userName = name//속성 이름을 만들면서 바로 매개변수 넣어줌
            this.userHeight = height;
            this.userWeight = weight;
            this.minWeight; 
            this.maxWeight; 
 
            this.getInfo = function(){
                var str = "";
                    str+= "이름: "+this.userName+", ";
                    str+= "키: "+this.userHeight+", ";
                    str+= "몸무게: "+this.userWeight+"<br>";
                return str;
            }
 
            this.getResult = function(){
                this.minWeight = (this.userHeight - 100* 0.9 - 5;
                this.maxWeight = (this.userHeight - 100* 0.9 + 5;
 
                if (this.userWeight >= this.minWeight &&
                    this.userWeight <= this.maxWeight) {
                    return "정상 몸무게입니다.";
                }else if(this.userWeight < this.minWeight){
                    return "정상 몸무게보다 미달입니다.";
                }else{
                    return "정상 몸무게보다 초과입니다.";
                }
            }
        }      
        var jang = new checkWeight("장보리",168,62);
        console.log(jang);
 
        document.write(jang.getInfo());
        document.write(jang.getResult()+"<br>");
        
        var park = new checkWeight("박달재",180,88);
        console.log(park);
 
        document.write(park.getInfo());
        document.write(park.getResult()+"<br>");
    </script>
</head>
cs

 

- 필드에 해당하는 속성들은 매개변수의 값을 받아서 바로 생성

- 계산 결과는 화면에 출력하고, 계산 과정은 콘솔에 출력하도록

- 각각의 객체로 2개의 함수를 모두 받아서 호출

- 객체 생성은 함수에 매개변수를 넣어서 바로 생성

 

프로토타입 - 메모리 절약

 

- 자바스크립트에서는 우측처럼 사용

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        function checkWeight(name, height, weight) {
            this.userName = name;
            this.userHeight = height;
            this.userWeight = weight;
            this.minWeight; 
            this.maxWeight; 
        }
 
        checkWeight.prototype.getInfo = function(){
                var str = "";
                    str+= "이름: "+this.userName+", ";
                    str+= "키: "+this.userHeight+", ";
                    str+= "몸무게: "+this.userWeight+"<br>";
                return str;
            }
 
        checkWeight.prototype.getResult = function(){
                this.minWeight = (this.userHeight - 100* 0.9 - 5;
                this.maxWeight = (this.userHeight - 100* 0.9 + 5;
 
                if (this.userWeight >= this.minWeight &&
                    this.userWeight <= this.maxWeight) {
                    return "정상 몸무게입니다.";
                }else if(this.userWeight < this.minWeight){
                    return "정상 몸무게보다 미달입니다.";
                }else{
                    return "정상 몸무게보다 초과입니다.";
                }
            }      
        var jang = new checkWeight("장보리",168,62);
        console.log(jang);
 
        document.write(jang.getInfo());
        document.write(jang.getResult()+"<br>");
        
        var park = new checkWeight("박달재",180,88);
        console.log(park);
 
        document.write(park.getInfo());
        document.write(park.getResult()+"<br>");
    </script>
</head>
cs

- 메모리가 절약된다는 점 외에는 위의 코드와 결과는 동일하게 출력

 

<예제>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        function TestScore(name, kor, eng) {
            this.userName = name;
            this.korNum = kor;
            this.engNum = eng;
        }
            TestScore.prototype.getTestInfo = function(){
                document.write("이름: "+this.userName+"<br>");
                document.write("국어: "+this.korNum+"<br>");
                document.write("영어: "+this.engNum+"<br>");
            }
            TestScore.prototype.getAvg = function(){
                return (this.korNum+this.engNum)/2
            }
 
            var kimgun = new TestScore("김군",80,90);
            var ohgun = new TestScore("오군",100,80);
 
            kimgun.getTestInfo();
            document.write("평균 점수:"+kimgun.getAvg(),"<br><br>");
            ohgun.getTestInfo();
            document.write("평균 점수:"+ohgun.getAvg(),"<br>");
    </script>
</head>
<body>
    
</body>
</html>
cs

 

내장함수

 

<예제>

 

728x90

'학원 > javascript-학원' 카테고리의 다른 글

객체  (0) 2022.03.17
제어문  (0) 2022.03.17