ES6) static& 구조분해 할당

소정·2023년 5월 25일

WEB_FRONT

목록 보기
18/20

1.static

클래스 생성 없이 사용 가능한 static 함수 있음

2.구조분해 할당

  • 객체의 특정 멤버를 뽑아서 일반변수에 대입하려 사용하는 문법
  • {} 중괄호로 클래스 안에 내가 원하는 변수만 가져올 수 있음
<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS es6 c class</title>
</head>
    <body>
            
        <script>
            //static 멤버
            class first {
                static show() {
                    document.write(`static method show <br>`)
                }

                static name = "kim" //멤버 변수 일때만 static키워드 붙일 수 있다

                constructor() {
                    // static this.age = 20 //error
                }
            }

            //객체 생성 없이 사용가능
            first.show()
            
            //staitc 멤버변수
            document.write(` ${first.name} <br>`)

            // staitc도 클래스 설계 밖에서 추가할 수 있음
            first.num = 50
            document.write(` ${first.num} <br>`)

        </script>

        <hr>

        <script>

            //구조분해 할당 문법.!!!!!!!!!!
            //리액트에서 좋아함 중요~
            class Nice {
                name = "hong"
                age = 20
                address = "seoul"
            }

            let nice = new Nice()
            document.write(`name : ${nice.name} <br>`)
            document.write(`name : ${nice.age} <br>`)
            document.write(`address : ${nice.address} <br>`)

            //객체의 특정 멤버를 뽑아서 일반변수에 대입하려 사용하는 문법
            // let name = nice.name
            // let age = nice.age
            let {name, age} = nice //나이스 안에서 네임을 꺼내온 모습
            
            document.write(`name2 : ${name} <br>`)
            document.write(`age2 : ${age} <br>`)

            //구조분해 할당이 가장 많이 활용되는 형태는 - 함수에 파라미터로 객체를 전달
            //예)nice 객체의 주소(address)를 출력해주는 기능 함수
            function showNiceAddress({address}) { //어드레스를 보내면 그 안에 address변수만 받겠다
                document.write(`address : ${nice.address} <br>`)
            }

            showNiceAddress(nice) //객체를 파라미터로 전달

            //구조분해 할당 주의점 : 멤버의 이름이 다르면 할당 불가능
            // ..? 당연한 이야기 아님.,,? 없는데,,,어케 찾음,,,?
            let {addess} =nice
            document.write(`address : ${addess} <br><hr>`)



            //특이한 구조분해 할당
            //특정멤버를 제외한 나머지들을 하나의 객체로 할당
            class Hello {
                aaaa = 10
                bbbb = 20
                cccc = 30
                dddd = 40
            }

            let hello = new Hello()
            const {aaaa, ...rest} = hello // ...rest : 나머지 멤버들을 가지는 객체
            document.write(`aaaa : ${aaaa} <br>`)
            document.write(`bbbb : ${rest.bbbb} <br>`)
            document.write(`cccc : ${rest.cccc} <br>`)
            document.write(`dddd : ${rest.dddd} <br>`)


        </script>

    </body>
</html>
profile
보조기억장치

0개의 댓글