[TIL]Javascript Classes

DevelSopher·2021년 8월 8일
0
post-thumbnail

그동안, 클래스형 컴포넌트를 사용하며 프로젝트를 다수 진행했었습니다.

일종의 컨벤션처럼 클래스형 컴포넌트는 이런식으로 생겼어 라는 생각하며 별생각없이 받아들였는데

이번 기회 자바스크립트에서의 Class는 정확히 뭔지 개념을 정리하고자 합니다. 🔥

Class

Class는 객체를 생성하기 위한 템플릿입니다.
클래스는 데이터와 이를 조작하는 코드를 하나로 추상화 합니다.
(from MDN)

class PersonClass {
  constructor(name, age, gender){
    this.name = name;
    this.age = age;
    this.gender = gender;
  }
  
  getInfo(){
    return this.name + this.age + this.gender
  }
}
//인스턴스 생성
const Person1 = new PersonClass("Jun",27,"Male")

Person1.getInfo() //'Jun27Male'

객체를 쉽게 생성하는 템플릿또는이라고 생각하면 됩니다.

클래스 특성

1. 여기서 PersonClass 앞의 new 키워드는 반드시 필요합니다.

이것이 class의 constructor를 호출하기 때문입니다.

1 Class => 1 Constructor

2. constructor를 클래스에 추가하지 않는다면, default로 빈 constructor가 자동으로 추가됩니다.

3. Hoisting

const Person1 = new PersonClass() // ReferenceError

class PersonClass() //선언부

함수 선언의 경우 Hoisting이 발생하여 자동으로 참조가 되지만
클래스 선언의 경우 Hoisting이 일어나지 않아 위 같은 결과가 나옵니다.

4. 정적메소드

정적메소드 is 프로토타입 위에 있는 것이 아닌 클래스 자체 함수
static 키워드를 앞에 선언

class PersonClass {
  constructor(name, age, gender){
    this.name = name;
    this.age = age;
    this.gender = gender;
  }
  
  getInfo(){
    return this.name + this.age + this.gender
  }
  
  static getGender(v) {
    return v.gender
  }
}

const Person1 = new PersonClass("Jun",27,"Male")

PersonClass.getGender(Person1)

여기서 주목해야 할 점은, PersonClass.getGender 클래스의 인스턴스에서 호출할 수 없다는 점입니다.
클래스의 인스턴스를 생성하지 않고 호출이 됩니다.

5.Getters/Setters
Getter

class Foo {
  constructor(arr=[]){
    this._arr = arr;
  }
  
  get firstElem(){
    
    return this._arr.length ? this._arr[0] : null;
  }
}

const foo = new Foo([1,2]);

console.log(foo.firstElem) // 1

Setter

class Foo {
  constructor(arr=[]){
    this._arr = arr;
  }
  
  get firstElem(){
    
    return this._arr.length ? this._arr[0] : null;
  }
  
  set firstElem(elem){
    this._arr = [elem, ...this._arr];
  }
}

const foo = new Foo([1,2]);
foo.firstElem = 100

console.log(foo.firstElem) // 100

6.클래스 상속
클래스 상속은 extends라는 키워드로 수행이 가능합니다.
클래스 상속을 통해 코드의 재사용성을 높힐 수 있습니다.

class PersonClass {
  constructor(name, age, gender){
    this.name = name;
    this.age = age;
    this.gender = gender;
  }
  
  getInfo(){
    return this.name + this.age + this.gender
  }
}
// 클래스 상속
class SubPersonClass extends PersonClass{
  getInfo(){
    return this.name + this.age + this.gender + " this is child class"
  }
}

const Person1 = new SubPersonClass("Jun",27,"Male")

Person1.getInfo(); // Jun27Male this is child class

Child Class에서 Parent Class에 선언된 함수를 그대로 불러와야 할 순간이 있습니다.
그때 바로, super라는 키워드를 사용합니다.

class PersonClass {
  constructor(name, age, gender){
    this.name = name;
    this.age = age;
    this.gender = gender;
  }
  
  getInfo(){
    return this.name + this.age + this.gender
  }
}

class SubPersonClass extends PersonClass{
  getInfo(){
    return super.getInfo() + " plus subclass"
  }
}

const Person1 = new SubPersonClass("Jun",27,"Male")

Person1.getInfo(); /// Jun27Male plus subclass
profile
💎다듬고 연마하자👑

0개의 댓글