프로토타입과 클래스

유슬기·2023년 1월 16일
0

프론트엔드

목록 보기
26/64
post-thumbnail

프로토타입

JavaScript는 프로토타입 기반 언어이며, 프로토타입(Prototype)은 원형 객체를 의미한다.
프로토타입은 객체의 특성을 다른 객체로 상속하는 것을 가능하게 하는 메커니즘이다.

아래 예시로 살펴보자.

class Human {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sleep() {
    console.log(`${this.name}은 잠에 들었습니다`);
  }
}

let kimcoding = new Human('김코딩', 30);

Human.prototype.constructor === Human; // true
Human.prototype === kimcoding.__proto__; // true 
Human.prototype.sleep === kimcoding.sleep; // true
  • Human 클래스의 생성자 함수는 Human이다.
  • Human 클래스의 prototype은 Human 클래스의 인스턴스인 kimcoding의 __proto__이다.
  • Human 클래스의 sleep 메서드는 prototype에 있으며, Human 클래스의 인스턴스인 kimcoding에서 kimcoding.sleep으로 사용할 수 있다.

위의 예시에서 Human(클래스)와 kimcoding(인스턴스, 아래 그림에선 steve), 프로토타입의 관계

Array(배열) 클래스와 인스턴스, 프로토타입의 관계 또한 위의 그림과 원리가 동일하다.

배열(arr)은 Array 클래스의 인스턴스이며, 프로토타입에는 다양한 메서드가 존재한다.

프로토타입 체인

  • 객체 지향 프로그래밍의 특성 중 상속을 구현할 때 사용된다.
  • 자바스크립트에서는 extendssuper 키워드를 이용해서 상속을 구현할 수 있다.
  • 속성과 메서드를 물려주는 클래스를 부모 클래스, 속성과 메서드를 물려받는 클래스를 자식 클래스라고 한다.
  • __proto__를 이용하면 부모 클래스의 프로토타입, 혹은 '부모의 부모 클래스'의 프로토타입을 탐색할 수 있다.

아래 mdn 링크에서 클래스 상속을 구현하는 법을 이해하고 연습해보자.

Classes in JavaScript ECMAScript 2015 클래스

아래와 같이 Person class가 정의되어 있을 때,

class Person {
  constructor(first, last, age, gender, interests) {
    this.name = {
      first,
      last
    };
    this.age = age;
    this.gender = gender;
    this.interests = interests;
  }

  greeting() {
    console.log(`Hi! I'm ${this.name.first}`);
  };

  farewell() {
    console.log(`${this.name.first} has left the building. Bye for now!`);
  };
}

new 키워드로 Person의 인스턴스를 생성할 수 있다.

let han = new Person('Han', 'Solo', 25, 'male', ['Smuggling']);
han.greeting(); // Hi! I'm Han

let leia = new Person('Leia', 'Organa', 19, 'female' ['Government']);
leia.farewell(); // Leia has left the building. Bye for now

Person클래스 →(상속)  Teacher 클래스 생성: 하위 클래스 생성

하위 클래스를 생성하기 위해 자바스크립트에서는 extends 키워드를 통해 상속 받을 클래스를 명시한다.
(Person의 first, last, age, gender, interests는 상속, subject, grade는 Teacher에 새로 추가)

class Teacher extends Person {
  constructor(first, last, age, gender, interests, subject, grade) {
    this.name = {
      first,
      last
    };

  this.age = age;
  this.gender = gender;
  this.interests = interests;

  // subject와 grade는 Teacher 클래스에 새로 추가(Teacher 클래스 전용 속성)
  this.subject = subject;
  this.grade = grade;
  }
}

super 키워드를 사용하면 상위 클래스의 생성자를 호출하며, 매개변수를 통해 상위 클래스의 멤버를 상속받을 수 있다.

class Teacher extends Person {
  constructor(first, last, age, gender, interests, subject, grade) {
		// super 키워드를 사용하여 코드를 간결하게 줄일 수 있다.    
		super(first, last, age, gender, interests);

  // subject와 grade는 Teacher 클래스에 새로 추가(Teacher 클래스 전용 속성)
  this.subject = subject;
  this.grade = grade;
  }
}

Teacher의 인스턴스를 생성하면 의도한대로 Teacher와 Person 양 쪽의 메소드와 속성을 사용할 수 있다.

let snape = new Teacher('Severus', 'Snape', 58, 'male', ['Potions'], 'Dark arts', 5);
snape.greeting(); // Hi! I'm Severus.
snape.farewell(); // Severus has left the building. Bye for now.
snape.age // 58
snape.subject; // Dark arts
profile
아무것도 모르는 코린이

0개의 댓글