[JS] Class 선언, Getter & Setter, 상속과 다양성

Janet·2022년 8월 31일
0

JavaScript

목록 보기
7/26
// 1. Class declarations

class Person {
    // constructor
    constructor(name, age) {
        // fields
        this.name = name;
        this.age = age;
    }
    // methods
    speak() {
        console.log(`$(this.name): hello!`);
    }
};
// Create a new object
const jiyaho = new Person('jiyaho', 20);
console.log(jiyaho.name); // jiyaho
console.log(jiyaho.age); // 20
jiyaho.speak(); // jiyaho: hello!


// 2. Getter and Setters
class User {
    constructor(firstName, lastName, age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
    // 값을 리턴하는 get
    get age() {
        return this._age;
    }
    // 값을 설정하는 set
    set age(value) {
        if (value < 0) {
            throw Error('age can not be negative');
        }
        this._age = value;
    }
}
const user1 = new User('Steve', 'Jobs' -1);
console.log(user1.age); // Error('age can not be negative')


// 3. 상속과 다양성

class Shape {
    constructor(width, height, color) {
        // fields 3개
        this.width = width;
        this.height = height;
        this.color = color;
    }
    // methods 2개
    draw() {
        console.log(`drawing ${this.color} color of`);
    }
    getArea() {
        return width * this.height;
    }
}
// 새로운 클래스를 만드는데 기존 클래스인 Shape를 extends를 통해 연장 및 상속하여 사용 가능
class Rectangle extends Shape {}

// Rectangle Class가 Shape Class를 상속하였기에 아래 새로운 Object에서도 draw 및 getArea method가 정상 작동함
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw(); // drwaing blue color of
console.log(rectangle.getArea()); // 400

// Shape의 method인 getArea를 수정 즉, overwriting하여 사용할 수 있다. => 다양성
// overwriting 한 method는 수정된 내용으로 출력되는데, 만약 기존 class의 method 또한 그대로 받고 싶다면 super를 통해 호출 가능
class Triangle extends Shape {
    getArea() {
        return (width * this.height) / 2;
    };
    draw() {
        super.draw(); // Shape의 draw method를 그대로 상속받는 코드: super.method명()
        console.log('triangle!!');
    };
};
const triangle = new Rectangle(20, 20, 'red');
triangle.draw();
// drawing red color of
// triangle!!
console.log(triangle.getArea()); // 200
profile
😸

0개의 댓글