javascript - class

DonQ·2021년 2월 28일
0

TIL

목록 보기
30/31
post-thumbnail

javascript는 클래스를 생성할수 있다.
드림코딩으로 공부하며, 공부한 내용을 블로그에 정리해볼까 한다.

1. 클래스 선언

class Person{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
    speak(){
        console.log(`${this.name}: hello!`);
    }
}

const donq = new Person('donq', 34);
console.log(donq.name); //donq
console.log(donq.age); //34
donq.speak(); //donq: hello!

클래스에는 메소드도 선언할수 있다.

2. Getter and Setter

class User{
    constructor(firstName, lastName, age){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
  /*getter 와 setter 선언 이유는 미선언 시 
  age와 같은 값을 -값으로 설정 할 경우 확인을 못하기 때문이다.
  그래서 -값을 줬을경우 0이라고 출력한다 */
    get age() {
        return this._age;
    }
    set age(value){
        this._age = value < 0 ? 0 : value; // 0보다 작을경우 0을 출력한다.
    }
}

const dq = new User('Q','lee',30);
console.log(dq);

3. Inheritance

class Shape{
    constructor(width, height, color){
        this.width = width;
        this.height = height;
        this.color = color;
    }
    draw() {
        console.log(`drawing ${this.color} color of`);
    }
    getArea() {
        return this.width * this.height;
    }
}
class Rectangle extends Shape {}; //Shape를 상속함 
class Triangle extends Shape { //Shape를 상속하나 오버라이딩한다.
    draw(){
        super.draw(); // 부모클래스의 메소드를 쓸 그대로 쓸 경우 super를 써준다.
        console.log('세모');
    };
    getArea(){
        return (this.width * this.height)/2;
    };
};
const rectangle = new Rectangle(20,20,'blue');
rectangle.draw();
console.log(rectangle.getArea());
const triangle = new Triangle(20,20,'red');
triangle.draw();
console.log(triangle.getArea());

4.Class checking : instanceOf

console.log(rectangle instanceof Rectangle);  // true
console.log(triangle instanceof Rectangle); // false
console.log(triangle instanceof Shape); // true
console.log(triangle instanceof Object); // true

클래스 내에 인스턴스로 있는지 확인 하는 방법

profile
꾸준히 쌓아가는 코딩 Study

1개의 댓글

comment-user-thumbnail
2021년 2월 28일

와 정리봐 .. 대박

답글 달기