IT/JS

Class

프티 2021. 5. 20. 15:55
반응형

JS Classes

 

es6에서 소개되었으며,

기존 js에 문법적으로 추가된 것이다(완전히 새로운 것이 아님).

이를 syntactical sugar이라고 한다.

 

클래스는 붕어빵 기계의 틀과 같다고 할 수 있다.

 

이 틀에 반죽과 팥이라는 data를 넣었을때,

만들어진 붕어빵은 Object와 같다고 할 수 있다.

 

즉 클래스를 활용하여 다양한 오브젝트를 만들 수 있는 것이다(단팥, 피자, 초코 붕어빵 등등..).

 

  • 클래스의 이름은 대문자로 시작하는 규칙이 있다.
    class Person{
        //constructor
        constructor(name,age){
            //field
            this.name=name; //this:생성된 오브젝트의 name
            this.age=age;
        }
        //methods
        speak(){
            console.log(`${this.name}: hello!`);
        }
    }​
    
    //새로운 오브젝트를 만들때는 new라는 키워드 사용
    const ellie = new Person('ellie', 20);
  • getter, setter
    class User{
        constructor(firstName, lastName, age){
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
        }
        get age(){
            return this._age;
        }
    
        set age(value){
            //if (value < 0){
            //  throw error('age can not be negative');
            //}
            this._age = value < 0 ? 0 : value;
            }
    }
    
    const user1 = new User('steve','job',-1);
    console.log(user1.age);​
    get과 set이 class 내에서 구체적으로 정의되었다면,
    정의된 property에 한해서 accessor(접근자)로 작용하게 된다.

    위의 코드에서 user1.age에 의해 User 오브젝트의 this.age에 접근하는 즉시,
    get과 set을 호출한다.

    먼저 set에 의해 this.age의 값을 정의하는데,
    class의 this.age와 이름이 같다면 infinite recursion(무한 반복)이 일어나 overstack flow되므로,
    set의 this._age처럼 다른 이름으로 정의해주어야 한다.

    삼항 조건 연산자를 활용하여 값을 새롭게 정의하면,
    get에 의해 이 값이 리턴되어 this.age가 아닌 this._age가 화면에 출력된다.
  • ingeritance 상속
    extends를 사용하면 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{}
    
    const rectangle = new Rectangle(20,20,'blue');
    rectangle.draw();
    
    class Triangle extends Shape{//다형성의 특징을 보여준다.
        draw(){
            super.draw(); // super: 최상위 클래스를 의미
            console.log('세모');
        }
        getArea(){
            return (this.width*this.height) / 2;
        }
    }
    
    const triangle = new Triangle(20,20,'blue');
    console.log(triangle.getArea());
    triangle.draw();​
  • class checking: instanceOf
    instance를 기준으로 왼쪽의 오브젝트가 오른쪽의 오브젝트로 만들어졌는지 boolean 값으로 알려주는 기능
    console.log(rectangle instanceof Rectangle); // true
    console.log(triangle instanceof Rectangle); // false
    console.log(triangle instanceof Triangle); // true
    console.log(rectangle instanceof Shape); // true
    console.log(triangle instanceof Object); // true
    // --> 모든 오브젝트는 Object에 속해있다.​

 

 

반응형