클래스
란 어떠한 속성 또는 행동을 가지고 있는 특정한 사물을 생성하기 위한 템플릿이다.
속성
이란 해당 객체를 나타낼 수 있는 특징행동
은 객체가 할 수 있는 동작책
자동차
컴퓨터
음식
영화
class Movie {
title = '';
genre = '';
runningTime = '';
constructor(title, genre, runningTime) {
this.title = title;
this.genre = genre;
this.runningTime = runningTime;
}
getReadableRunningTime() {
const hours = Math.floor(this.runningTime / 60);
const minutes = this.runningTime % 60;
return `${hours}시간 ${minutes}분`;
}
}
const movie = new Movie('명량', '전쟁/액션', 90);
console.log(movie.title); // 출력: 명량
console.log(movie.genre); // 출력: 전쟁/액
const readableRunningTime = movie.getReadableRunningTime();
console.log(readableRunningTime); // 출력: 1시간 30분
class Computer {
os = '';
ram = '';
constructor(model, os, ram) {
this.os = os;
this.ram = ram;
}
start() {
console.log(`${this.os} 운영체제가 가동중...`);
console.log('시작완료!');
}
end() {
console.log(`${this.os} 운영체제가 종료됩니다...`);
console.log('종료 완료!');
}
executeProgram(program, ram) {
if (this.ram < ram) {
console.log(`${program} 실행 불가`);
} else {
console.log(`${program} 실행 시작!`);
}
}
}
const pc방컴퓨터 = new Computer('Windows 10', '100GB');
pc방컴퓨터.start(); // 출력: Windows 10 운영체제가 가동중
pc방컴퓨터.executeProgram('GTA6', '20GB'); // 출력: GTA6 실행 시작
const 학교컴퓨터 = new Computer('Linux', '2GB');
학교컴퓨터.start(); // 출력: Linux 운영체제가 가동중
학교컴퓨터.executeProgram('GTA6', '20GB') // 출력: GTA6 실행 불가
객체
란 어떠한 속성 또는 행동을 정의하여 가지고 있는 특정한 사물이다.
속성
이란 해당 객체를 나타낼 수 있는 특징행동
은 객체가 할 수 있는 동작객체의 예시
특정한 제목, 줄거리, 출판사, 지은이를 속성으로 가지는 만화책
특정한 모델, 운영체제, RAM 용량을 속성으로 가지는 윈도우 컴퓨터
특정한 주 재료, 칼로리, 무게를 속성으로 가지는 김치
특정한 제작 회사, 장르, 러닝 타임을 속성으로 가지고, 킬링 타임 소리를 출력하는 영화
자바스크립트에서의 객체는 변수 키워드(const, let, var)
와 중괄호 {}
를 사용하여 속성의 이름과 값을 지정하여 선언할 수 있다. (값은 변수, 함수, 객체 등 다양한 형태가 올 수 있다.)
콤마 ,
를 찍어줘야 한다.<aside>
💡 클래스의 객체
와 중괄호 {} 객체
의 차이점
private 접근 제한자
사용 가능extends
를 활용한 상속 가능
2-1. 객체의 prototype을 통한 상속은 use strict에서 불가능결론: 간단한 구조라면 중괄호 {}를 사용, 객체간 중복되는 로직이 많다면 클래스를 사용하는것이 좋다.
</aside>
객체명.프로퍼티명
문법을 통해 객체의 값에 접근할 수 있다.const comicBook = {
title: '명탐정코난',
summary: '초등학생으로 변한 코난의 검은조직 파훼치기',
writer: '아오야마 고쇼',
};
console.log(book.title) // 명탐정코난
console.log(book.writer) // 아오야마 고쇼
const cheolsoo = {
age: 14,
gender: 'male',
nickname: '코딩의 신',
friend: {
name: '짱구',
age: 14,
isSmart: false,
},
isSmart: true,
};
console.log(cheolsoo.age) // 14
console.log(cheolsoo.nickname) // 코딩의 신
console.log(cheolsoo.friend.name) // 짱구
console.log(cheolsoo.friend.isSmart) // false
const cat = {
color: 'brown',
height: '50cm',
cryingSound: () => {
const time = '20:00';
if (time < '21:00') {
return '야옹';
} else {
return '야오오오오오옹';
}
}
}
console.log(cat.color) // brown
console.log(cat.cryingSound()) // 야옹