JS/드림코딩앨리

6. 클래스와 오브젝트의 차이점(class vs object), 객체지향 언어 클래스 정리

배워도끝이없네 2021. 4. 21. 10:08
'use strict';
//class : 템플릿이다
//object : 클래스를 이용해서 실제로 데이터를 넣어 만든것
//javaScript classes
// -introduced in ES6
// -기존에 존재하던 prototype을 기반해서 문법만 class가 추가된것.

// 1.Class declarations
class Person{
    //constructor
    constructor(name,age){
    //fields
    this.name = name;
    this.age = age;
}


//methods
    speak(){
        console.log(`${this.name} : hello`);
    }
}

const ellie = new Person('ellie',20);
console.log(ellie.name);
console.log(ellie.age);

//2. Getter and setter
class User{
    constructor(fristName, lastName, age){
        this.fristName = fristName;
        this.lastName = lastName;
        this.age = age;
    }

    get age(){  //getter 를 정의하는 순간 this.age 는 메모리에 저장된값을 불러오는것이 아니라 getter를 호출함.
        return this._age;
    }

    set age(value){ //setter를 정의하는 순간 =age는 setter를 호출하게됨. 
        // if(value<0){
        //     throw Error('age can not be negative');
        // }
        // this._age = value < 0 ? 0 : value;
        this._age = value;
    }
}

const user1= new User('steve','job',-1);
console.log(user1.age);


//3. Field (public , private)
// 너무 최근에 추가되어서 지금은 사용을 많임하지않음

class Experiment{
    publicField = 2; 
    #privateField = 0;  //<<< #을 붙이면 private화 됨
}
const experiment = new Experiment();
console.log(experiment.publicField);
console.log(experiment.privateField);


class Example{
    constructor(world){
        console.log("생성자호출됨");
        this.hello = world;
    }

    get hello(){
        return this._hello;
    }

    set hello(value){
        this._hello=value;
    }
}
const obj = new Example(100);
console.log(obj.hello);


//4. Static properties and methods
// 오브젝트와 상관없이 공통적으로 class에서 사용하는것이라면 static메소드를 사용한다.
class Article{
    static publisher = 'Dream Coding';
    constructor(articleNumber){
        this.articleNumber = articleNumber;
    }

    static printPublisher(){
        console.log(Article.publisher);
    }
}

const article1 = new Article(1);
const article2 = new Article(2);
console.log(article1.publisher); 

//5. Inheritance //상속
// a way for one class to extend another class.
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{} // extends를 통해 반복되는 코드를 줄일수 있다 (다형성)
class Triangle extends Shape{
    draw(){
        super.draw();
        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());

    //6. Class checking : instanceOf //왼쪽에 있는 object가 오른쪽 클래스를 이용해서 만들어진아인지 아닌지 true/false로 반환
    console.log(rectangle instanceof Rectangle);
    console.log(triangle instanceof Rectangle);
    console.log(triangle instanceof Triangle);
    console.log(triangle instanceof Shape);
    console.log(triangle instanceof Object);