본문 바로가기

개발/자바스크립트∥

[자바스크립트] 클래스와 인스턴스 생성

반응형


ES6부터 클래스를 만드는 새 문법이 도입되었습니다. 클래스선언과 클래스표현으로 클래스를 구현할 수 있습니다.

1. class Car 생성하기


class Car{

    constructor(make,model){

        this.make = make;

        this.model = model;

        this._userGears = ['P', 'N', 'R', 'D'];

        this._userGear = this._userGears[0];

    }

    shift(gear){

        if(this._userGears.indexOf(gear)<0)

            throw new Error(`Invalid gear: ${gear}`);

        this._userGear=gear;

    }

}

2. class Car 호출하기


// car1, car2 객체 생성

const car1 = new Car("Tesla", "Model S");

const car2 = new Car("Mazda", "3i");



// 각 객체 shift메서드에 변수인자값 입력

car1.shift('D');

car2.shift('R');



//userGear 프로퍼티 

car1.userGear // "D"

car2.userGear // "R"


shift 메서드를 잘못사용하면 에러처리가 되지만, car1.userGear = 'X' 처럼 직접 설정하면 에러처리가 되지 않습니다.

3. WeakMap인스턴스를 이용한 class 생성

  • 스코프를 이용해 보호하는 WeakMap인스턴스를 사용해 봅시다.

const Car =(function(){



    const carProps = new WeakMap();



    class Car{

        constructor(make,model){

            this.make = make;

            this.model = model;

            this._userGears = ['P', 'N', 'R', 'D'];

            carProps.set(this,{userGear: this._userGears[0]});

        }

        get userGear() { return carProps.get(this).userGear;}

        set userGear(value){

            if(this._userGears.indexOf(value)<0)

                throw new Error(`Invalid gear: ${value}`);

            carProps.get(this).userGear = value;

        }

        shift(gear){this.userGear = gear;}

    }

    return Car;

})();

함수 표현식을 써서 WeakMap을 클로저로 감싸고 바깥에서 접근할 수 없게 했습니다.

참고 책 : Learning JavaScript (이서 브라운 지음, 한빛미디어)

반응형