#17. Class Syntax(2)

2langk·2021년 3월 23일
0

[오분자스 - 개념편]

목록 보기
17/24
post-thumbnail

Class Syntax(2)

이번에는 클래스 문법으로 클래스를 상속하는 방법에 대해 소개해보려한다.

아래는 지난번에 소개했던 prototype으로 상속하는 코드이다.
Book이 Magazine에게 상속해주고 있다.

---Book

function Book(title, author, year) {
    this.title = title;
    this.author = author;
    this.year = year;
}

Book.prototype.getSummary = function () {
    return `${this.title} was book`;
};



---Magazine

function Magazine(title, author, year, month) {
    Book.call(this, title, author, year);
    this.month = month;
}

Magazine.prototype = Object.create(Book.prototype)

Magazine.prototype.constructor = Magazine; 

const mag1 = new Magazine('my mag', 'lee', 2021, 03)

mag1.getSummary() // "my mag was book" 

동일한 코드를 클래스 문법으로 바꿔보겠다.

class Book {
	constructor(title, author, year){
    	    this.title = title;
	    this.author = author;
	    this.year = year;
	}

	 getSummary() {
	     return `${this.title} was book`;
	 };
}

class Magazine extends Book { // (1)
	constructor(title, author, year, month){
		super(title, author, year) // (2) 
		this.month = month
	}
}

const mag1 = new Magazine('my mag', 'lee', 2021, 03)

mag1.getSummary() // "my mag was book" 

(1) 상속받을 클래스를 extends 키워드로 명시해준다.
(2) constructor안에서 super(...)를 호출한다.

이게 클래스에서 상속하는 방법이다. 프로토타입 문법에 비해 훨씬 간결하다.
동일하게 mag1 객체에서 Book의 prototype에 접근이 가능한 것을 확인할 수 있다.

오늘은 여기서 마무리하고, 다음에는 OOP의 특징에 대해 소개하면서 OOP 시리즈를 끝내야겠다.

0개의 댓글