개발일지
개발일지 41일차
index.ys
2023. 4. 28. 22:05
Class
- 객체지향 프로그래밍에서 특정 객체를 생성하기 위해 변수와 메소드를 정의하는 틀이다
- 객체를 정의하기 위한 상태, 멤버 변수와 메서드로 구성됨
- 동일한 object를 뽑는 기계
기본문법
- 클래스를 정의 할때는 "class" 키워드를 사용하여 클래스 정의, 생성사 함수, 메서드로 이루어짐
- 객체를 생성하기 위해 "new" 연산자를 사용하여 생성
예제1
//클래스 선언
class User {
constructor(이름 , 나이) {
this.name = 이름; // this.name = kim
this.age = 나이; //this.age = 20
}
sayHi() {
//kim입니다, 20 살입니다
console.log(`${this.name}입니다, ${this.age} 살입니다`);
}
}
// 사용법:
let user1 = new User("kim", "20");
let user2 = new User("lee", "32");
user.sayHi();
- User 클래스는 '이름' 과 '나이' 속성을가지고 sayHi메서드를 가지고 있음
- new User로 user1, user2 객체를 생성하고 sayHi로 호출한 결과를 콘솔로 출력함
예제2
// 도형 클래스
class Shape {
constructor(width, height) {
this.width = width;
this.height = height;
}
// 넓이 구하는 메서드
getArea() {
return this.width * this.height;
}
}
// 직사각형 클래스
class Rectangle extends Shape {
constructor(width, height) {
super(width, height);
}
// 둘레 구하는 메서드
getPerimeter() {
return 2 * (this.width + this.height);
}
}
// 객체 생성
const rectangle = new Rectangle(5, 10);
console.log(rectangle.getArea()); // 출력 결과: 50
console.log(rectangle.getPerimeter()); // 출력 결과: 30
- 'Shape' 클래스는 width와 height 속성을 가지며 'getArea' 메서드를 가지고 있음
- 'Rectangle' 클래스는 'Shape' 클래스를 상속받아 'getPerimeter' 메서드를 추가로 가지고 있음
- 'Rectangle' 클래스를 이용해 'rectangle' 객체를 생성하고 'getArea' 함수와 'getPerimeter' 메서드를 호출함
예제3
// 스택 클래스
class Stack {
// 생성자
constructor() {
//클래스 필드: 변수선언
//Stack 클래스의 모든 인스턴스에서 공유되는 배열 items
this.items = [];
}
// 스택에 아이템 추가
push(item) {
//클래스 바디
//[item1, item2,item3]
this.items.push(item);
}
// 스택에서 아이템 삭제
pop() {
//클래스 바디
//[ item1, item2 ]
return this.items.pop();
}
// 스택에서 가장 최근 아이템 반환
peek() {
//클래스 바디
// item2
return this.items
}
shift() {
//클래스 바디
return this.items.shift()
}
}
// 객체 생성
const stack = new Stack();
// 아이템 추가
stack.push('apple');
stack.push('banana');
stack.push('orange');
stack.push('kiwi');
stack.push('melon');
// 가장 최근 아이템 반환
console.log(stack.peek()); // [ 'apple', 'banana', 'orange', 'kiwi', 'melon' ]
//맨뒤 아이템 삭제
console.log(stack.pop()) //melon
//맨앞 아이템 삭제
console.log(stack.shift()) //apple
// 가장 최근 아이템 반환
console.log(stack.peek()); // [ 'banana', 'orange', 'kiwi' ]
- 'Stack' 이라는 클래스 생성 'items'는 배열속성을 가짐
- push(item) 메서드: 배열에 새로운 아이템을 추가
- pop() 메서드: 가장 최근에 추가된 아이템을 삭제하고 삭제된 아이템을 반환
- shift() 메서드 : 가장 먼저 추가된 아이템을 삭제하고 삭제된 아이템을 반환
- peek() 메서드 : 스택의 상태를 확인
- 클래스 바디: class Stack{ ... } 중괄호 내부 전체
- 클래스 필드: items = [] 클래스 필드는 생성자나 메서드 내부가 아닌 클래스 바디 내부에 선언되는 변수
- 생성자와 메서드: 클래스 바디 내부에서 선언된 함수