Day5_VSCODE_JavaScript_ (재정리) _클래스 심화

2023. 4. 11. 12:48Javascript

 

static 

 정적 프로퍼티 및 메소드를 생성

프로그램이 실행되면서 무조건 바로 메모리에 올라가는 것

클래스안에 메소드 예)(Static MakeBanana)는 this 참조할 수 없다

 

        class Fruit {
            static count_fruit = 10;
            constructor(name,emoji){
                this.name = name;
                this.emoji = emoji;
            }
            display = () => {
                console.log(`${this.name}: ${this.emoji}`)
            }

            static makeBanana(){
                return new Fruit('banana','🍌')
            }
        }

        const apple = new Fruit('apple','🍎')
        const orange = new Fruit('orange','🍊')
        console.log(apple)
        console.log(orange)
        console.log(apple.name)
        console.log(orange.name)
        console.log(Fruit.count_fruit)

        const banana =Fruit.makeBanana();
        console.log(banana)

 

private

프로퍼티의 순수성을 지키기위해 사용하는 것

(주로 프로퍼티를 사용해야하면 함수를 이용해서 사용한다.)

 

        class Dog{
            #name;  //private 이라고 함 (접근이 불가능함.)
            #color;
            constructor(name,color) {
                this.#name = name;
                this.#color = color;
            }

            //private에 접근 시, 프로퍼티 명과 꼭 일치할 필요는 없음
            set name(value){
                console.log('set',value)
                this.#name = value
            }
            get name(){
                return`이름:${this.#name}`
            }
            run = () => {
                console.log(`${this.#color} 색상의 강아지 ${this.#name}이 달립니다.`)
            }

            #eat = () => {
                console.log(`${this.#name}은 먹습니다.`)        //메소드접근 불가 시키기
            }
            colorEat = () =>{
                this.#eat();
            }
        }

 

 

728x90