class란??
- 현실과 비슷한 개념(객체)을 나타내기 위한 도구를 **클래스(Class)**라고 부릅니다.
- 클래스는 미리 정의해놓으면 필요할 때마다 해당 클래스로 동일한 틀을 가진 객체를 만들 수 있습니다.
- 여기서 동일한 클래스를 이용해 생성한 객체를 **인스턴스(Instance)**라고 부릅니다.
class User {
}
const 사람 = new User();
사람.name = "오길환";
사람.age = 29;
사람.tech = "Node.js";
console.log(사람.name); // 오길환
console.log(사람.age); // 29
console.log(사람.tech); // Node.js
생성자(Constructor)
👉 “클래스 내부에서 constructor()로 정의한 메서드를 "생성자"라고 부릅니다.
미리 정의한 클래스를 기반으로 인스턴스를 생성할 때 Javascript 내부에서 호출되는 메서드인데요. 아래와 같이 사용할 수 있습니다.
class User {
constructor(name, age, tech) { // User 클래스의 생성자
this.name = name;
this.age = age;
this.tech = tech;
}
}
const 사람 = new User("오길환", 29, "Node.js"); // user 인스턴스 생성
console.log(사람.name); // 오길환
console.log(사람.age); // 29
console.log(사람.tech); // Node.js
this 와 property
생성자의 바디에서 this 키워드를 사용합니다. 이 this는 클래스를 사용해 만들어 질 객체 자신을 의미하고 this 뒤에 붙는 name, age, tech는 클래스를 이용해서 만들어질 객체의 속성(Propety)입니다.
class User {
constructor(name, age, tech) { // User 클래스의 생성자
this.name = name;
this.age = age;
this.tech = tech;
}
}
const 사람 = new User("오길환", 29, "Node.js"); // user 인스턴스 생성
console.log(사람.name); // 오길환
console.log(사람.age); // 29
console.log(사람.tech); // Node.js
생성자를 이용해 name, age, tech인자값을 입력받아 class 내부변수에 저장합니다.
메서드(method)
자바스크립트에서 사용할 수 있는 모든 값은 프로퍼티 값으로 사용할 수 있는데요. 프로퍼티 값이 함수일 경우에는 일반 함수와 구분하기 위해 **메서드(Method)**라고 부릅니다.
즉, 메서드는 객체(Object) 에 묶여 있는 함수를 의미합니다.
클래스에서도 데이터를 나타내는 속성뿐만아니라 함수와 같이 특정 코드를 실행할 수 있는 문법을 사용할 수 있는데요, 여기서는 Class라는 객체(Object)에 묶여있는 함수를 **메서드(Method)**라고 부릅니다.
class User {
constructor(name, age, tech) { // User 클래스의 생성자
this.name = name;
this.age = age;
this.tech = tech;
}
getName() {
return this.name;
} // getName 메서드
getAge() {
return this.age;
}
// getAge 메서드
getTech() {
return this.tech;
} // getTech 메서드
}
상속이란??
일반적으로 클래스의 인스턴스는 선언한 클래스의 기능을 모두 상속합니다.
상속을 이용해 부모 클래스와 자식 클래스로 나뉠 수 있는데요. 부모 클래스의 경우 메서드, 내부 변수와 같은 정보를 자식 클래스에게 할당해줄 수 있습니다.
그렇다면 상속을 이용하여 자식 클래스를 생성해볼까요?
아래의 예제는 우선 User 클래스를 정의하고, Employee라는 이름의 새로운 클래스가 User를 상속합니다. 생성자 내부의 super()는 생성자 내에서만, 그리고 this 키워드를 사용하기 전에만 쓸 수 있습니다.
- Employee를 User의 서브 클래스로 정의합니다.
- User의 자식 클래스인 Employee에서 User.getTech() 메서드를 호출합니다.
class User { // User 부모 클래스
constructor(name, age, tech) { // 부모 클래스 생성자
this.name = name;
this.age = age;
this.tech = tech;
}
getTech() {
return this.tech;
} // 부모 클래스 getTech 메서드
}
class Employee extends User { // Employee 자식 클래스
constructor(name, age, tech) { // 자식 클래스 생성자
super(name, age, tech);
}
}
const employee = new Employee("이용우", "28", "Node.js");
console.log(employee.name); // 이용우
console.log(employee.age); // 28
console.log(employee.getTech()); // 부모 클래스의 getTech 메서드 호출: Node.js
Quiz !!!
❓ 요구 사항에 맞는 클래스를 완성해주세요!
- 요구 사항
- Unit 클래스를 만든다.
- 클래스 생성자에서 내부변수 name, hp를 정의한다.
- healing, damaged 메서드를 정의한다.
- healing 메서드는 hp를 올릴 수 있고 hp가 100이 넘을 경우 더이상 회복되지 않는다.
- damaged 메서드는 hp를 감소 시킬 수 있고 hp가 0이 넘을 경우 더이상 감소되지 않는다.
- hp가 0이 되었을 경우 더이상 healing 메서드와 damaged 메서드가 동작하지 않는다.
내가 작성한 코드
class Unit {
constructor(name,hp){
this.name = name;
this.hp = hp;
}
healing(num) {
if(this.hp >= 100 || this.hp === 0 ){
} else if(this.hp += num > 100) {
this.hp = 100
} else{
this.hp += num
};
}
damaged(num) {
this.hp -= num
if(this.hp < 0){
this.hp = 0
}
}
};
const monster = new Unit('바퀴벌레',98);
console.log(monster.damaged(99))
console.log(monster.hp)
'JavaScript&TypeScript' 카테고리의 다른 글
파이썬 JS Python Dictionary와 JavaScript Object (0) | 2022.12.16 |
---|---|
JavaScript Array 자주 쓰이는 내장함수 복습하기 (0) | 2022.12.16 |
JavaScript Error handling 에러 핸들 (0) | 2022.12.12 |
Javascript 동기(Sync)&비동기(Async) (0) | 2022.12.12 |
JavaScript 고급 함수 forEach() (1) | 2022.12.10 |
댓글