211006 TIL
[codecademy]JAVASCRIPT SYNTAX, PART III
자바스크립트 구문 파트 3에 진입하면서 클래스에 대한 기초적 지식을 배울 수 있었다.
클래스는 객체를 만들기 위한 템플릿 역할로 중복 코드와 디버깅 시간을 줄이는 좋은 메소드다.
Build a Library 문제
상황
축하합니다. 당신의 도움이 절실히 필요한 지역 Books-'N-Stuff의 수석 사서가 되셨습니다.
이곳은 여전히 인덱스 카드를 사용하여 콘텐츠를 구성하고 있습니다!
하지만 여러분은 자바스크립트를 알고 있기 때문에, 현대화하는 작업에 착수해 봅시다.
Books-N-Stuff에는 Book, CD, Movie 등 세 가지 종류의 미디어가 들어 있습니다.
이 프로젝트에서는 Book, CD, Movie 세 개의 하위 class가 있는 Media라는 부모 class 만듭니다.
Specify
- 부모 클래스, Media는 Book, CD, Movie 세 가지 하위 클래스를 생성한다.
- 세 가지 하위 클래스는 아래와 같은 속성과 메서드를 가진다.
- Book
Properties: author (string), title (string), pages (number), isCheckedOut (boolean, initially false), and ratings (array, initially empty).
Getters: all properties have a getter
Methods: .getAverageRating(), .toggleCheckOutStatus(), and .addRating() - Movie
Properties: director (string), title (string), runTime (number), isCheckedOut (boolean, initially false), and ratings (array, initially empty)
Getters: all properties have a getter
Methods: .getAverageRating(), .toggleCheckOutStatus(), and .addRating() - CD
Properties: artist (string), title (string), isCheckedOut (boolean, initially false), and ratings (array, initially empty), songs (array of strings)
Getters: all properties have a getter
Methods: .getAverageRating(), .toggleCheckOutStatus(), and .addRating()
- Book
Ideate
Media클래스를 생성한다.Media클래스의constructor()을 생성한다.
세 가지 하위 클래스의 공통 프로퍼티는title,isCheckedOut,ratings다.
isCheckOut과ratings프로퍼티는 기본 값이 있기 때문에title만counstructor인수로 한다.constructor내부 프로퍼티를 설정한다.
이때,constructor내부의this는 클래스가 생성한 인스턴스를 가리킨다.
생성할 인스턴스가 해당 프로퍼티 값이 필요하다면this를 붙여야 상속받을 수 있다.constructor내부 프로퍼티에 접근할 수 있도록 저장된 값을 반환하는 각각의getter함수를 생성한다.isCheckOut은 메서드 호출에 따라 값을 변경해야하므로setter함수를 생성한다.- 세 가지 하위 클래스의 공통 메서드인
.toggleCheckOutStatus(),.getAverageRating()그리고.addRating()를Media메서드로 정의한다. .toggleCheckOutStatus()메서드는 호출 시isCheckout의 부울 값을 반전시킨다.
!논리 부정 연산자를 사용하면 쉽게 반전시킬 수 있다..getAverageRating()메서드는ratingsSum이라는 이름의 변수를 생성한 후ratings프로퍼티에 있는 배열의 요소들을 합산한 값을 할당한다.
평균값을 구해야하기 때문에ratingsSum변수 값을ratings프로퍼티의 배열 길이만큼 나눈 후 반환한다.addRating을 메서드는 새로운rating값인value를 인수로 받아ratings프로퍼티의 배열 요소에 추가한다.Media클래스의 하위 클래스인Book클래스를 생성한다.
extends키워드는 부모 클래스인Media의 메소드를 사용할 수 있도록 상속을 돕는다.
super키워드는 부모 클래스인Media의constructor()을 호출한다.
때문에 공통 프로퍼티였던title값을 인수로 전달해야Media의constructor()이 실행될 때this._title = title;이 새로 생성될Book인스턴스에 설정된다.
super()호출을 완료하면Book클래스만 가지고 있는author과pages프로퍼티를 생성한다. 그렇지 않으면 자바스크립트에서 참조 오류가 발생한다. 참조 오류를 방지하려면 하위 클래스constructor()의 첫 번째 줄에super을 호출하는 것이 가장 좋다.
constructor()생성이 끝나면Book클래스의 새로 생성한 프로퍼티들의getter함수도 생성한다.Media클래스의 하위 클래스인Movie클래스를 생성한다.
Movie클래스만 가지고 있는director과runTime프로퍼티를 생성하고getter함수도 생성한다.Media클래스의 하위 클래스인CD클래스를 생성한다.
CD클래스만 가지고 있는artist와songs프로퍼티를 생성하고getter함수도 생성한다.
Implement
class Media {
constructor(title) {
this._title = title;
this._isCheckedOut = false;
this._ratings = [];
}
get title() {
return this._title;
}
get isCheckedOut() {
return this._isCheckedOut;
}
get ratings() {
return this._ratings;
}
set isCheckedOut(value) {
this._isCheckedOut = value;
}
toggleCheckOutStatus() {
this.isCheckedOut = !this.isCheckedOut;
}
getAverageRating() {
let ratingsSum = this._ratings.reduce((a, c) => a + c);
return ratingsSum / this.ratings.length;
}
addRating(value) {
this._ratings.push(value);
}
}
class Book extends Media {
constructor(title, author, pages) {
super(title);
this._author = author;
this._pages = pages;
}
get author() {
return this._author;
}
get pages() {
return this._pages;
}
}
class Movie extends Media {
constructor(title, director, runTime) {
super(title);
this._director = director;
this._runTime = runTime;
}
get director() {
return this._director;
}
get runTime() {
return this._runTime;
}
}
class CD extends Media {
constructor(title, artist, songs) {
super(title);
this._artist = artist;
this._songs = songs;
}
get artist() {
return this._artist;
}
get songs() {
return this.songs;
}
}
const historyOfEverything = new Book(
"A Short History of Nearly Everything",
"Bill Bryson",
544
);
historyOfEverything.toggleCheckOutStatus();
console.log(historyOfEverything.isCheckedOut);
historyOfEverything.addRating(4);
historyOfEverything.addRating(5);
historyOfEverything.addRating(5);
console.log(historyOfEverything.getAverageRating());
const speed = new Movie("Jan de Bont", "Speed", 116);
speed.toggleCheckOutStatus();
console.log(speed.isCheckedOut);
speed.addRating(1);
speed.addRating(1);
speed.addRating(5);
console.log(speed.getAverageRating());
Author And Source
이 문제에 관하여(211006 TIL), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@sozero/211006-TIL저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)