라라리라

2023.10.19 / Step 7 [DOM_member] - 코딩 72 일차 본문

코딩/2023 JavaScript DOM

2023.10.19 / Step 7 [DOM_member] - 코딩 72 일차

헤실 2023. 10. 19. 23:23

_01_member_this개념1.html

<!DOCTYPE html>
<html lang="ko">
<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>
</head>
<body>
   
    <script>
        class Fruit {
            name = "";
            price = 0;

            printInfo() {
                // 클래스 내의 요소(변수,함수)에 접근할 때에는 반드시 this.을 붙여야 한다.
                console.log(this.name + " : " + this.price);
            }
        }

        let apple = new Fruit();
        apple.name = "사과";
        apple.price = 1000;
        apple.printInfo();
        //예상 => 사과 : 1000

    </script>

</body>
</html>

 


_01_member_this개념2.html

<!DOCTYPE html>
<html lang="ko">
<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>
</head>
<body>
   
    <script>
        class Fruit {
           
            start() {
                // 함수 안에서 this.을 붙여 클래스 변수를 생성할 수 있다.
                this.name = "";
                this.price = 0;
               
            }

            printInfo() {
                console.log(this.name + " : " + this.price);
            }
        }

        let apple = new Fruit();
        apple.name = "사과";
        apple.price = 1000;
        apple.printInfo();
       

    </script>

</body>
</html>

 


_01_member_화살표함수개념.html

<!DOCTYPE html>
<html lang="ko">
<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>
</head>
<body>

    <div id="target1">클릭1</div>
    <div id="target2">클릭2</div>
   
    <script>
        class Ex {

            num = 10;
           
            start() {
                let $target1 = document.querySelector("#target1");
                let $target2 = document.querySelector("#target2");

                $target1.addEventListener("click", this.target1Event);
                $target2.addEventListener("click", this.target2Event);
            }

            target1Event() {
                // this가 이벤트에 해당하는 대상으로 바뀌어 버림!
                console.log(this); // == <div id="target1">클릭1</div>
            }

            // 클래스 내에서 이벤트 처리 함수는 화살표 함수로 작성해야 한다.
            target2Event = (event) => {
                console.log("num = " + this.num); // this => class 내부변수 호출
                console.log(event.target.innerHTML); // event => 클래스 외부 이벤트에 접근
            }
           
        }

        let e = new Ex();
        e.start();

    </script>

</body>
</html>