본문 바로가기
JS/JS 핵심 개념

JS 클래스

by spare8433 2023. 3. 13.

클래스

 

이전의 생성자를 이용 한 타입 생성과 클래스는 정확히 그 결과가 일치한다.

 

기존의 자바스크립트의 타입 생성 방법을 다른 언어와 비슷하도록 보기 쉽게 문법을 개선한 것이 자바스크립트 클래스이다.

 

익플에서 적용 안됨

 

※ 내부적인 동작은 동일하지만 더 보기 좋고 편리하게 개선된 문법을 슈가 신텍스(Syntactic sugar)라고 한다

 

기본 모양새

 

  • 생성자 부분 constructor 함수 안에서 생성하고 속성을 바로 선언
  • function 키워드없이 메서드 이름으로 바로 생성

 

class User {
    constructor(name) {
        this.name = name;
    }
    sayName() {
        console.log(this);
        console.log(this.name);
    }
}

var me = new User("jaehyun");
me.sayName();

 

클래스 상속

 

extends 연산자를 이용해 상위 타입의 프로퍼티를 상속 받는 것이 가능

 

만약 자식 클래스에 constructor 함수를 선언하면 부모클래스의 constructor 함수를 덮어 쓰기 때문에 super 메소드를 통해 자식클래스의 생성자 함수가 부모 클래스의 생성자 함수를 덮어 씌우는 것을 방지 할 수 있습니다.

 

class Sausage {
    constructor(el1, el2) {
        this.inside1 = el1;
        this.inside2 = el2;
    }

    taste() {
        return this.inside1 + "와 " + this.inside2 + " 맛이 난다!";
    }
}

class FireSausage extends Sausage {
    constructor(el1, el2, el3) {
        super(el1, el2);    // 생성자 상속
        this.inside3 = el3;
    }

    flavor() {
        return this.inside3 + "의 풍미도 있다!";
    }
}

var classicFireSausage = new FireSausage("소고기", "파", "불맛");

console.log(classicFireSausage.taste());
console.log(classicFireSausage.flavor());

 

참고

https://www.inflearn.com/course/%EC%BD%94%EB%94%A9%EC%9D%B8%ED%84%B0%EB%B7%B0-js-%EC%96%91%EC%84%B1%ED%95%99%EA%B5%90

'JS > JS 핵심 개념' 카테고리의 다른 글

JS BOM (Browser Object Model)  (0) 2023.03.14
JS hoisting  (0) 2023.03.13
JS 프로토타입 상속 & subtype, supertype  (0) 2023.03.13
JS 프로토타입  (0) 2023.03.13
JS 생성자  (0) 2023.03.13