티스토리 뷰
코딩테스트/알고리즘 & 자료구조 개념
[자료구조 | JS] 자료구조를 배우기 전에 기본적으로 알아야하는 개념 ES2015 "class"
blueprint-12 2023. 3. 5. 21:59class(클래스)?
: 객체를 만들기 위한 프로퍼티와 메서드가 명시된 청사진
- 이 청사진에 기반한 객체들을 인스턴스화할 수 있다.
- 엄밀히 말하자면 JS는 실제로 클래스를 지원하지 않는다.(JS에 이미 존재하는 프로토타입 기반 상속자들을 구문적으로 눈속임한 syntatical sugar이다.) -> 진정한 OOP는 지원하지 않음
- 프로토타입 기반 상속자 혹은 프로토타이핑으로 불리는 무엇인가를 이용하는 것
- new 키워드를 통해 생성되거나 인스턴스화 된다.
- 생성자 함수는 클래스가 인스턴스화 할 때 동작하는 특별한 함수이다.
클래스를 왜 배워야할까🤔?
앞으로 수 많은 자료 구조들을 클래스(ES2015최신 문법)로 구현할 것이기 때문이다.
1. class syntax (문법)
class Student {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
- class명은 카멜케이스를 사용한다.(대문자 시작)
- constructor()는 새로운 스튜던트 인스턴스를 인스턴스화시킬 때 사용되는 특별한 메서드이다.
1-1. 클래스를 통해 새로운 인스턴스 생성하기
:클래스로부터 새로운 객체를 인스턴스화하는 방식 => new 키워드 사용
let firstStudent = new Student('gamza', 'kim');
let secondStudent = new Student('alex', 'chang');
- 각각은 기본적으로 위의 청사진(클래스) 패턴에 기반하는 새로운 Student 객체를 생성하게 된다.
class Student {
constructor(firstName, lastName, year) {
//this를 생성자 함수 내부에서 사용허게 되면, 개발 클래스 인스턴스 즉 개별 Student 인스턴스를 지칭하게 됩니다.
this.firstName = firstName;
this.lastName = lastName;
this.grade = year;
}
}
let firstStudent = new Student('gamza', 'kim');
let secondStudent = new Student('alex', 'chang');
secondStudent.grade = 4;
console.log(secondStudent.grade); //4
2. Instance methods(인스턴스 메서드)
: 클래스 단위에서 동작하는 것이 아니라 개별 인스턴스에 관련된 메서드
class Student {
constructor(firstName, lastName, year) {
//this를 생성자 함수 내부에서 사용허게 되면, 개발 클래스 인스턴스 즉 개별 Student 인스턴스를 지칭하게 됩니다.
this.firstName = firstName;
this.lastName = lastName;
this.grade = year;
this.tardies = 0;
this.scores = [];
}
fullName() {
return `your full name is ${this.firstName} ${this.lastName};`;
}
markLate() {
this.tardies += 1;
if (this.tardies >= 3) {
return 'you are expelled';
}
return `${this.firstName} ${this.lastName} has been late ${this.tardies} times`;
}
addScores(score) {
this.scores.push(score);
return this.scores;
}
calculateAverage() {
if (this.scores.length === 0) {
return "there's no scores";
}
let sum = this.scores.reduce((acc, crr) => acc + crr);
return Math.floor(sum / this.scores.length);
}
}
let firstStudent = new Student('gamza', 'kim', 1);
let secondStudent = new Student('alex', 'chang', 2);
console.log(firstStudent.markLate()); //gamza kim has been late 1 times
console.log(firstStudent.markLate());
console.log(firstStudent.markLate()); //you are expelled
firstStudent.addScores(83);
firstStudent.addScores(55);
console.log(firstStudent.calculateAverage()); //69
2-1. Class Methods(클래스 메서드)
클래스 메서드 = static 메서드
📌 "static" 키워드와 static method ?
- 이 static 키워드는 클래스에 종속되는 반면 클래스의 개별 인스턴스 메서드에는 반드시 종속적일 필요가 없는 메서드 혹은 기능들을 생성하도록 해준다.
- 거의 사용하진 않는다.
- ⭐ static 키워드는 스태틱 메서드를 만들어주며 스태틱 메서드는 클래스의 인스턴스화 없이도 호출될 수 있으며 클래스 인스턴스를 통해서는 호출될 수 없다. -> 어플리케이션을 위한 유틸리티 기능을 생성하기 위해 자주 사용된다.
- 즉, static 메서드는 특정 인스턴스와는 무관하며 일반적인 종합 기능 혹은 유틸리티 펑션 등과 같이 그냥 필요한 클래스의 한 부분이라고 할 수 있다.
// *static method(class method)
{
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static distance(a, b) {
//? 두 점 사이의 거리를 계산하는 거리 공식 사용
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.hypot(dx, dy);
}
}
const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
console.log('p1', p1);
console.log('p2', p2);
console.log(Point.distance(p1, p2)); //7.0710678118654755
}
'코딩테스트 > 알고리즘 & 자료구조 개념' 카테고리의 다른 글
[자료구조 | JS ] 단일 연결 리스트(single linked list)와 배열(Array) (0) | 2023.04.17 |
---|---|
[알고리즘 | JS] sorting algorithm(정렬 알고리즘)6 - radix sort (0) | 2023.02.24 |
[알고리즘 | JS] sorting algorithm(정렬 알고리즘)5 - quick sort (1) | 2023.02.23 |
[알고리즘 | JS] sorting algorithm(정렬 알고리즘)4 - merge sort (0) | 2023.02.22 |
[알고리즘 | JS] sorting algorithm(정렬 알고리즘)3 - insertion sort (0) | 2023.02.21 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- reactAPI
- 프리온보딩 프론트엔드 챌린지 3월
- 항해99추천비추천
- D 플래그
- tilde caret
- Prittier
- text input pattern
- getServerSideProps
- 원티드 프리온보딩 프론트엔드 챌린지 3일차
- 항해99프론트
- 항해99프론트후기
- && 셸 명령어
- 프리렌더링확인법
- is()
- grid flex
- ~ ^
- 형제 요소 선택자
- 원티드 FE 프리온보딩 챌린지
- 타입스크립트 DT
- nvm 설치순서
- 타입스크립트 장점
- 원티드 프리온보딩 FE 챌린지
- fs모듈 넥스트
- 틸드와 캐럿
- nvm경로 오류
- 원티드 3월 프론트엔드 챌린지
- aspect-ratio
- 부트캠프항해
- float 레이아웃
- getStaticPaths
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함