익명함수

익명함수는 변수에 함수를 설정하는 방법입니다.

익명함수

익명함수는 함수에 이름이 없기 때문에 변수에 넣어서 사용하는 함수입니다. 변수에는 숫자, 문자도 들어갈 수 있지만 함수도 들어갈 수 있습니다.

let 변수 이름 = function(){ //실행코드 } 변수 이름(); //함수 호출

샘플1

function func1(){
    document.write("함수가 실행되었습니다1.<br>");
}
func1();

let func2 = function(){
    document.write("함수가 실행되었습니다2.<br>");
}
func2();

//함수가 실행되었습니다1.
//함수가 실행되었습니다2.

샘플2

함수 호출문이 먼저 나와도 호이스팅 방식이 적용되어 정상적으로 함수를 호출한다.

let count = 0;
myFnc();

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

myFnc();

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

//hello1
//hello2
//bye3

샘플3(배경색 바꾸기)

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>javascript37</title>
    <script>
        let color = ["white", "yellow", "aqua", "purple"];

        //document.write(color[0]);

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

            let bodyTag = document.getElementById("theBody");
            bodyTag.style.backgroundColor = color[i];
            console.log("i: " + i);
            console.log("color[i] :" + color[i]);
        }

        
    </script>
    <!-- <style>
        #theBody {
            background: khaki;
        }
    </style> -->
</head>
<body id = "theBody">
    <button onclick = "changeColor();">배경색 바꾸기</button>
</body>
</html>

Last updated

Was this helpful?