본문 바로가기

Webstoryboy

Category

Explanation

JAVASCRIPT

[Javascript] 익명 함수

익명 함수

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


익명 함수

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

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

Sample1

함수를 사용하는 기본 예제입니다.

결과
function가 실행되었습니다.
html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        var func2 = function(){
            document.write("function가 실행되었습니다.");
        }
        func2();   
    </script>
</head>
<body>
    
</body>
</html>

Sample2

백그라운 색을 변경하는 예제입니다.

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

        let i = 0;
        function changColor(){
            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>
</head>
<body id="theBody">
    <button onclick="changColor();">배경색 바꾸기</button>
</body>
</html>

더보기

인스타그램 보기 바로가기

포트폴리오 스터디 바로가기

유튜브 영상보기 바로가기