[JS] Class

404·2022년 6월 20일
0

JS ❤️ TS

목록 보기
4/6
post-thumbnail

들어가며

그동안 몰랐었던 class에 대해서 공부했다. 타입스크립트를 사용한 객체지향 프로그래밍 강의를 들으며 깨달은 점인데 그동안 OOP에 대해서 완전 무지한 상태였고 일반 JS 환경에서도 class를 다뤄본적 없기 때문에 이번 기회에 조금이나마 공부해본다.

Class

githup 주소

class User {
   constructor(name) {
     this.username = name;
   }
   introduce() {
     console.log(`hi, my name is ${this.username}`);
   }
};

const newUser = new User("FUNco");
console.log(newUser.username); // 'FUNco'
newUser.introduce(); // "hi, my name is FUNco"

class란 객체를 찍어내는 공장과 같다. class를 정의한 뒤에 new 생성자와 함께 객체를 생성할 수 있으며 객체 안에는 해당 객체와 관련된 메소드를 제약 없이 넣을 수 있다.

예를들어 User라는 객체 안에 회원가입, 탈퇴, 정보변경 등 메소드를 정의해두고 user.create() user.delete()와 같이 사용하여 가독성과 재사용성을 높일수 있을것이다.

  • 조금 더 실용적인 예제
class User2 {
  constructor(name, email, password) {
    this.username = name;
    this.email = email;
    this.password = password;
  }
  sayHello() {
    console.log(`Hello, my name is ${this.username}`);
  }
  getProfile() {
    console.log(`${this.username} ${this.email} ${this.password}`);
  }
  updatepassword(newpassword, currentpassword) {
    if (currentpassword === this.password) {
      this.password = newpassword;
      console.log("password changed!");
    } else {
      console.log("can't change password");
    }
  }
}

const sexyUser2 = new User2("FUNco", "111@com", "1234");

sexyUser2.sayHello(); // Hello, my name is FUNco
sexyUser2.updatepassword("new password", "123456"); // can't change password
sexyUser2.updatepassword("new password", "1234"); //  password changed!
sexyUser2.getProfile(); // FUNco 111@com new password

위 예시처럼 객체 생성, 수정 등 많은 메소드를 내장하여 사용할 수 있다.

class의 확장 (extends)

class Admin extends User2 {
  deleteWebsite() {
    console.log("Boom!");
  } // 메소드 추가
}

const sexyAdmin = new Admin("FUNco", "111@com", "1234");

sexyAdmin.getProfile(); // FUNco 111@com 1234
sexyAdmin.deleteWebsite(); // Boom!

User2 클래스를 상속받은 (== User2 클래스를 확장하여) Admin class를 생성했다.
클래스의 확장이 없었다면 User2 클래스를 정의했을때 처럼 똑같은 코드를 반복해서 적어야 할것이다. 확장은 이러한 반복을 줄여준다. 상속받은 클래스의 메소드를 그대로 사용할 수 있으며 추가로 새로 생성한 클래스 고유의 메소드를 추가해줄수도 있다.

  • super

여기서 새로 만든 Admin 클래스에 구조를 변경해줘야 한다면 어떻게 될까? sexyAdmin 인스턴스에 더 많은 속성을 추가해야한다면?

class Admin extends User2 {
  constructor(name, email, password, newOne, newTwo) {
    super(name, email, password); //constructor() 에 새로운 인자를 받고 super()을 통해서 base class인 User2의 속성을 넘겨받는다. 
    this.newOne = newOne;
    this.newTwo = newTwo;
  }
  deleteWebsite() {
    console.log("Boom!");
  }
  checkNew() {
    console.log(this.newOne, this.newTwo);
  }
}

const sexyAdmin = new Admin(
  "FUNco",
  "111@com",
  "1234",
  "I'm new one",
  "I'm new two"
);

sexyAdmin.getProfile(); //FUNco 111@com 1234
sexyAdmin.deleteWebsite(); // Boom!
sexyAdmin.checkNew(); // I'm new one I'm new two

느낀점

  • class의 활용은 정말 무궁무진할것 같다. 코드의 가독성과 재사용성을 높게 하는데 매우 유용할듯 하다. 많은 채용공고에서 OOP에 대한 경험과 이해를 우대사항 또는 자격사항에 넣곤 하는데 그 이유를 알것같다. 아직 원론적으로 OOP와 class에 대해 전부 이해한건 아니지만 프로잭트에 적용해보면서 차차 익숙해지길 기대한다.
profile
T.T

0개의 댓글