노드 입문_4

·2022년 12월 12일
0

클래스(Class)

미리 정의해놓으면 필요할 때마다 해당 클래스로 동일한 틀을 가진 객체를 만들 수 있음

인스턴스 = 동일한 클래스를 이용해 생성한 객체

class User { 
}

const user = new User();
user.name = "이용우";
user.age = 28;
user.tech = "Node.js";

console.log(user.name); // 이용우
console.log(user.age); // 28
console.log(user.tech); // Node.js

생성자(Constructor)
클래스 내부에서 constructor()로 정의한 메서드

class User {
  constructor(name, age, tech) { // User 클래스의 생성자
    this.name = name;
    this.age = age;
    this.tech = tech;
  }
}

const user = new User("이용우", 28, "Node.js"); // user 인스턴스 생성

console.log(user.name); // 이용우
console.log(user.age); // 28
console.log(user.tech); // Node.js

this와 프로퍼티(Property)

  • 생성자의 바디에서 this 키워드 사용
  • this는 클래스를 사용해 만들어 질 객체 자신을 의미
  • this 뒤에 붙는 name, age, tech는 클래스를 이용해서 만들어질 객체의 속성(Property)
  • 생성자를 이용해 name, age, tech 인자 값을 입력받아 class 내부변수에 저장
class User {
  constructor(name, age, tech) { // User 클래스의 생성자
    this.name = name;
    this.age = age;
    this.tech = tech;
  }
}

const user = new User("이용우", "28", "Node.js"); // user 인스턴스 생성
console.log(user.name); // 이용우
console.log(user.age); // 28
console.log(user.tech); // Node.js

메서드(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 메서드
}

const user = new User("이용우", "28", "Node.js"); // user 인스턴스 생성
console.log(user.getName()); // 이용우
console.log(user.getAge()); // 28
console.log(user.getTech()); // Node.js

상속

  • 부모 클래스의 경우 메서드, 내부 변수와 같은 정보를 자식 클래스에게 할당
  • 생성자 내부의 super()는 생성자 내에서만, 그리고 this 키워드를 사용하기 전에만 쓸 수 있음
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
  • super 키워드란?
    함수처럼 호출할 수도 있고, this와 같이 식별자처럼 참조할 수 있는 키워드
    super 키워드를 호출하면 부모 클래스생성자(constructor)를 호출합니다.
    super 키워드를 참조하면 부모 클래스메서드(Method)를 호출할 수 있습니다.
profile
개발자가 되는 과정

0개의 댓글