상세 컨텐츠

본문 제목

[자바스크립트] 즉시실행함수

카테고리 없음

by esoesmio 2023. 5. 23. 12:22

본문

<!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>Title</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: skyblue;
        }


    </style>
</head>
<body>
<div class="box">
</div>


<script>
    const box = document.getElementsByClassName("box")[0];
    //전역함수선언
    //어디에서든 호출 가느아
    function move() {
        //지역함수선언
        //선언된 코드블록(중괄호 블록) 안에서만 호출가능
        function changecolor() {
            box.style.background = 'red';
        }
changecolor();
        box.style.marginLeft = '200px';
    }


    console.log('haha');
    (function () {
        function changecolor2() {
            box.style.background = 'gold';
        }
        changecolor2();
        //즉시실행 함수 안의 지역함수라도 즉시 실행되지 않고 함수 호출 구문을 만들어줘야 지역함수가 실행된다.
    })();
    move();
    changecolor();
</script>
</body>
</html>

 

(function (a,b){
console.log(a);
console.log(b);
})('a','b');

 

 

 

 

 

 

 

댓글 영역