class
1. 선언
class Person{
consturctor(name, age){
this.name = name;
this.age = age;
}
speak(){
console.log(`${this.name} : hello`)
}
}
2. object 생성
const ellie = new Person('ellie', 20);
// ellie, 20이 this.name, this.age로 전달
3. getter / setter
- 사용자가 잘못된 값을 입력했을 때,
그것을 방지하기 위해 사용
- class Person{
constructor(name, age){
this.name = name;
this.age = age;
}
get age(){
// getter를 추가하면 this.age를 사용하려는 순간 this.age의 값을 불러오지 않고,
getter를 호출함
return this.age;
}
set age(value){
//setter를 추가하면, 아래에 적힌 this.age에 값을 할당하려는 순간,
값을 할당하지 않고 setter(set age(value))를 호출함
- 개발자가 사전에 정한 setter의 조건을 만족하는지 확인하기 위해
if(value<0){
console.log("age cannot be lower than 0"):
}
this.age = (value<0)?0:value;
}
speak(){
console.log(`name : ${this.name}, age : ${this.age}`);
}
const p1 = new Person('kim', 20);
p1.speak();
3-1. getter / setter 사용법
위 코드를 사용하면 오류가 발생하는 이유
A. setter의 경우
- new Person('kim', 20)을 통해 age에 값 할당시키려고 함
- set age(value) 호출
- if문 뒤, this.age = (value<0)?0:value;를 통해 this.age에 값 할당하려고 함
- set age(value) 호출
- if문 뒤, this.age = (value<0)?0:value를 통해 this.age에 값 할당하려고 함
- set age(value) 호출
- ......
B. getter의 경우
- p1.speak()를 통해 this.age를 사용하려고 함
- get age() 호출
- 내부의 return this.age를 통해 this.age 사용하려고 함
- get age() 호출
- 내부의 return this.age를 통해 this.age 사용하려고 함
- get age() 호출
- ....
이를 해결하기 위해서 get, set에 _를 붙여주자!
- get age(){
return this._age
}
- set age(value){
...this._age = ....;
}
_는 private, 또는 내부적인 속성이라는 뜻
const p1 = new Person("kim", -1) 을 통해 this.age에 -1을 할당하려는 순간,
set age(value)가 호출(이 때, value로는 -1이 들어갑니다)
this._age에 -1이 할당되고
p1.speak()를 통해 this.age가 사용되려는 순간,
get age()가 호출되어 this.age에 this._age의 값인 -1이 반환됨
3. public / private
- class Experiment{
publicfield = 2;
#privatefield = 0;
}
const experiment = new Experiment();
console.log(experiment.publicfield)
console.log(experiment.privatefield)
생성자를 쓰지 않고 class 내부에 field를 만들면
클래스의 필드에 대해 외부에서 접근이 가능하지만
#을 붙이면, 클래스 외부에서 접근 및 수정이 불가능해짐
4. static
- class Article {
static publisher = 'Dream Coding'
constructor(articleNumber){
this.articlenNumber = articleNumber;
}
static printPublisher(){
console.log(Article.publisher)
}
}
const article1 = new Article(1)
const article2 = new Article(2)
console.log(article1.publisher) // undefined
console.log(Article.publisher) // Dream Coding
class 내부에 static으로 선언된 field, method는
object에 할당되는 것이 아닌, class 원본에만 있는 것이여서
article1.publisher이 undefined가 나옴
5. 상속 / 다양성
- class Shape{
constructor(width, height, color)
this.width = width;
this.height = height;
this.color = color;
draw()
console.log(`drawing ${this.color} color of`)
getArea (){
return this.width * this.height;
}
}
위는 도형에 관한 class를 선언한 것
이는 삼각형, 사각형 등 다양한 도형 관련
class를 만들 때, 미리 공통된 속성이 있는
class를 만들어서 보다 적게 기술하기 위함
class Shape의 것을 쓰고 싶다면
class Rectangle extends Shape{} 로 작성,
이를 상속이라고 함(class (새 클래스 이름) extends (원본 class 이름))
다양성
- 도형의 넓이를 구한다 가정했을 때,
사각형과 삼각형의 넓이 구하는 공식이 다름
따라서, 각 class 마다 getArea method를 재구성해줘야 함
- class Triangle extends Shape{
getArea(){
return this.width * this.height / 2;
}
위와 같이 상속받은 class의 method를 재정의한 것을
메서드 오버라이딩 이라고 함(이 때, 원본의 원래 method는 호출 X)
cf) 오버라이딩했지만, 원본의 메소드를 호출하고 싶다면 super 키워드 이용
- super.draw();
6. instanceOf(왼쪽의 객체가 오른쪽 class에서 만들어진 것인지 boolean 값 return)
console.log(rectangle instanceOf Rectangle)
// t
console.log(triangle instanceOf Shape)
// Triangle은 Shape에서 상속되었으므로
t
'TIL > JavaScript' 카테고리의 다른 글
| String Method (0) | 2022.09.02 |
|---|---|
| map, set (0) | 2022.08.28 |
| 배열 관련 함수 (0) | 2022.05.22 |
| 배열(기초) (0) | 2022.05.21 |
| 객체(object) (0) | 2022.05.21 |