9.2.1 클래스와 인스턴스 생성

1) 클래스 생성

class Car {
    constructor() {
    }
}

2) 인스턴스 생성

  • new 키워드 사용

const car1 = new Car();
const car2 = new Car();

3) instanceof 연산자

  • 객체가 클래스의 인스턴스인지 확인하는 연산자

car1 instanceof Car // true
car1 instanceof Array // false

4) this 키워드

  • 메서드를 호출한 인스턴스를 가리키는 목적

  • 일종의 플레이스 홀더

  • 메서드를 호출하는 시점에서 this가 무엇인지를 알 수 있음

class Car {
    constructor(make, model) {
        this.make = make;
        this.model = model;
        this.userGears = ['P', 'N', 'R', 'D'];
        this.userGear = this.userGears[0];
    }
}

5) 메서드 생성

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;
    }
}

const car1 = new Car("Tesla", "Model S");
const car2 = new Car("Mazda", "3i");

car1.shift('D');
car2.shift('R');

car1.userGear; // D
car2.userGear; // R

6) 가짜 접근 제한 (_) 과 get, set

  • 위의 예제의 경우 car1.userGear = 'X' 라고 설정한다면 막을 수 없음

  • 자바스크립트에는 대부분의 객체지향 언어와 달리 메서드, 프로퍼티 접근 설정 메커니즘이 없음

  • 외부에서 접근하면 안 되는 프로퍼티 이름 앞에 밑줄을 붙임

class Car {
    constructor(make, model) {
        this.make = make;
        this.model = model;
        this._userGears = ['P', 'N', 'R', 'D']; // 외부에서 접근하면 안되는 프로퍼티
        this._userGear = this.userGears[0]; // 외부에서 접근하면 안되는 프로퍼티
    }
    
    get userGear() {
        return this._userGears;
    }
    
    set userGear(value) {
        if (this.userGears.indexOf(gear) < 0)
            throw new Error(`Invalid gear: ${gear}`);
        this.userGear = gear;
    }
    
    shift(gear) {
        this.userGear = gear;
    }
}

Last updated