Class
작성
1) class vs object
class
1. template
2. declare once
3. no data in
object
1. instance of a class
2. created many times
3. data in
2) getter, setter
- 이상한 값이 들어올 때 방어적으로 대응할 수 있다.
class User {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age() {
return this._age;
}
set age(value) {
if (value < 0) {
throw Error('age cannot be negative');
}
this._age = value;
}
}
- getter =
get age(){}를 정의하는 순간,this.age는 메모리에 올라와 있는 데이터를 읽어오는 것이 아니라,getter를 호출하게 된다. - setter =
set age(){}를 정의하는 순간,= age는 값을 할당할 때 바로 메모리의 값을 할당하는 것이 아니라setter를 호출하게 된다. - 그말은 setter 안에서 전달된 value를 this.age에 할당할 때 메모리의 값을 업데이트 하는 것이 아니라 setter를 호출하게 된다.
- 따라서 User의 프로퍼티에는 1)
_age만 존재하게 된다.
3) private, public
class Car {
publicField = 2;
#privateField = 0;
}
const Ford = new Car();
console.log(Ford.publicField); // 2
console.log(Ford.privateField); // undefiend
- #붙이면 프라이빗 필드가 된다.
- 최신 문법이기 때문에 babel 사용해야 한다.
4) Static
class Article {
static publisher = 'unitive';
constructor(articleNumber) {
this.articleNumbeer = articleNumber;
}
static printPublisher() {
console.log(Article.publisher);
}
}
const article1 = new Article(1);
console.log(article1.publisher); // undefined
console.log(Article.publisher); // unitive
Article.printPublisher(); // unitive
- static: 클래스안에서만 사용할 수 있는 프로퍼티
- 인스턴스에 일일이 값을 넣어주지 않고, class에만 정의하고 사용하니까 메모리를 효율적으로 사용할 수 있다.
5) 상속 & 다형성
class Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
console.log('now drawing');
}
getArea() {
return this.width * this.height;
}
}
class Rectangle extends Shape {}
class Triangle extends Shape {
getArea() {
return this.width * this.height * 0.5;
}
draw() {
super.draw(); //부모 draw호출
console.log('📐📐📐');
}
}
const rectangle = new Rectangle(20, 20, blue);
const triangle = new Triangle(20, 20, blue);
6) instanceof
console.log(rectangle instanceof Rectangle); //true
console.log(triangle instanceof Rectangle); // false
console.log(rectangle instanceof Shape); // true
console.log(rectangle instanceof Object); // trie
7) super()
super의 사용 이유
- 부모 클래스의 내용이 자식 클래스에도 비효율적으로 중복해서 존재하고 있을 때, 또는 자식 클래스에서 새로운 요소를 추가할때
super를 사용하면 코드의 재사용을 줄일 수 있다.
super의 2가지 용법
super(): 부모 클래스의 생성자(constructor)가 호출이 된다.super.method: 부모 클래스의 메서드를 가져다 쓸 수 있다.
class Person{
constructor(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
sum(){
return this.first+this.second;
}
}
class PersonPlus extends Person{
constructor(name, first, second, third){
super(name, first, second);
this.third = third;
}
sum(){
return super.sum()+this.third;
}
avg(){
return (this.first+this.second+this.third)/3;
}
}
var kim = new PersonPlus('kim', 10, 20, 30);
console.log("kim.sum()", kim.sum());
console.log("kim.avg()", kim.avg());