본문 바로가기

나혼자공부시간(평일저녁,주말,휴일때)

자바스크립트:함수 정의문: 호이스팅

 

함수 호이스팅 순서 알아보기

<script>
    var count = 0;
    
    myFnc(); //함수 호출문이 먼저 나와도 호잇팅 방식이 적용되어 정상적으로 함수를 호출합니다

    function myFnc(){
        count++;
        document.write("hello" + count,"<br>");
    }

    myFnc();

    var theFnc=function(){
        count++;
        document.write("bye" + count,"<br>");

    }

    theFnc();

</script>

 

 

함수 정의문 이용해 [배경색 바꾸기] 버튼 눌러 배경색 바뀌게 하기

<script>
    var color=["white", "yellow", "aqua","purple" ];

    var i =0;
    function changeColor(){
    i++;
    if(i>=color.length){
        i=0;
    }

    var bodyTag = document.getElementById("theBody"); 
    //.getElementById()메서드는 id값을 이용해 문서 객체(태그)를 선택하는 메서드.
    //CSS의 아이디 선택자와 비슷한 역할을 합니다.
    //선택한 문서 객체에 스타일을 적용하기 위해서는 다음과 같이 문서 객체의 style에 접근하고 적용하고자 하는 속성에 새 값을 입력해야 합니다.
    bodyTag.style.backgroundColor=color[i];
    //문서.style.스타일속성=새값
    //ex)id값이 "theBody"인 요소의 배경색를 노란색으로 적용합니다.
   // document.getElementByld("theBody").style.backgroundColor="yellow"

}
</script>
</head>
<body id="theBody">
    <button onclick="changeColor();">배경색 바꾸기</button>
</body>

 

매개변수있는 함수로 질의응답 창(prompt) 통해 아이디 , 비밀번호 경고 창 뜨게 하기

<script>
    var rightId="korea";
    var rightPw="1234";

    function login(id,pw){
        if(id==rightId){
            if(pw==rightPw){
                document.write("welcome!"+id); //올바른 아이디인경우
            }else {
            alert("That's wrong"+pw); //비번 틀린 경우
        }
        }else{
            alert(id+"doesn't exists"); // 틀린 비밀번호인 경우
        }
    }

    var userId = prompt("enter ID");
    var userPw = prompt("enter Password");

    login(userId,userPw)
</script>

 

 

평균값 구하기

<script>
   function testAvg(arrData){
    var sum = 0;
    for(var i=0; i<arrData.length; i++){
        sum +=Number(prompt(arrData[i] + `score?`,'0'));
    }

    var avg = sum/arrData.length;
    return avg;
   }

   var arrSubject = ["국어", "수학"];
   var result = testAvg(arrSubject);

   document.write("your average score is"+result);
</script>

 

 

 

재귀 함수 호출

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

        testFnc();
    }

    testFnc();
</script>

결과값

외부에 있는 함수호출이 먼저 가고 안에 있는 내부testFnc();가 또 호출함.

그래서 조건문 10이 되면 함수가 종료됨.

 

 

함수 스코프에 대한 이해

<script>
    var score = 10;

    function myFnc(){
        var score = 50;
        alert(score); //50
        //함수 스코프에서는 지역변수 데이터를 가져옵니다.
    }

    myFnc();

    alert(score); //10
    //함수 스코프 밖에서는 전역 변수 데이터를 가져옵니다.
</script>
<script>
    function myFnc(){
        alert("전역함수");
    }

    function outerFnc(){
        function myFnc(){
            alert("지역함수");
        }
        myFnc(); //지역함수 호출
    }
    outerFnc();
    myFnc(); // 전역 함수 호출
</script>

1.지역함수 먼저 나오고

2.전역함수 그 다음에 나온다.

 

전역과 지역을 나누는 이유: 전역과 지역을 나누면 충돌을 피하기 있음.만약 같은 이름의 전역 변수나 전역 함수를 사용하면 충돌이 발생한다. 아니면 변수나 함수의 이름이 같은 경우에도 충돌이 발생할수 있다

 

 

 

 

 

즉시실행함수

<script>
    (function(){
        var num = 100;
        function menu(){
            num +=100;
            alert(num);
        }
        menu();
    })(); // 첫 번째 함수 마지막에 괄호 추가

    (function(){
        var num = 100;
        function menu(){
            alert(num);
        }
        menu(); // 두 번째 함수 호출 추가
    })();
</script>

즉시실행함수: (function)을 감싸준거를 실행한거

 

 

1.함수 CheckWeight로 몸무게 표준인지 아닌지 알아내기

<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+'.';
            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, 42);
    var park = new CheckWeight('박달재', 180,88);
    console.log(jang);
    console.log(park);

    document.write(jang.getInfo()); 
    document.write(jang.getResult());
</script>

2.이건 프로토타입(Prototype)을 이용해서 다시 만든 코드

<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);
    var park = new CheckWeight("박찬호", 180, 88);

    document.write(jang.getInfo());
    document.write(jang.getResult());
    document.write(park.getInfo());
    document.write(park.getResult());

</script>

 

 

 

 

 

 

 

실습) getTestInfo() 함수를 실행하면 이름, 국어, 영어 정보를 출력하도록 작성해보세요.

getAvg()함수를 실행하면 평균 점수를 출력하도록 작성해보세요.

<script>
    function TestScore(name,kor,eng){
        this.userName=name;
        this.korNum = kor;
        this.engNum=eng;

        this.getTestInfo=function(){
            document.write("Name: "+this.userName,"<br>");
            document.write("Korean Score: "+this.korNum,"<br>");
            document.write("English Score: "+this.engNum,"<br>");
        }
        this.getAvg = function(){
            return(this.korNum+this.engNum)/2;
        }
    }

    var kimgun = new TestScore("Kim Gun", 80,90);
    var ohgun = new TestScore("Oh Gun", 100,30);

    kimgun.getTestInfo();
    document.write("평균점수: "+kimgun.getAvg()+ "<br><br>");
</script>