[Javascript] 프로토타입과 상속

SungWoo·2024년 10월 22일

자바스크립트 공부

목록 보기
10/42
post-thumbnail

자바스크립트는 프로토타입 기반의 프로그래밍 언어로, 객체는 다른 객체를 통해 프로퍼티와 메서드를 상속받을 수 있다. 지금부터 프로토타입이 뭔지 알아보도록 하자.

모든 객체는 프로토타입을 가진다.

자바스크립트에서 모든 객체는 [[Prototype]]이라는 내부 슬롯을 가지고 있으며, 이는 해당 객체가 상속받는 다른 객체를 가리킨다.

프로토타입 체인

객체가 특정 프로퍼티나 메서드를 호출할 때, 먼저 자신의 프로퍼티나 메서드에서 존재를 찾고 없으면 프로토타입을 통해 찾는다. 이를 통해 객체 간에 프로퍼티와 메서드를 공유할 수 있다.

자바스크립트로 프로토타입 상속을 구현하는 3가지 방법

1. 생성자 함수(Constructor Function)

  • 생성자 함수는 새로운 객체를 생성하기 위한 특수한 함수이다.
  • 일반적으로 대문자로 시작하는 이름을 사용하여 생성자 함수와 일반 함수를 구분한다.
  • 생성자 함수를 호출할 때는 new 키워드를 사용해야한다.
function Person(name, age) {
  this.name = name; // 속성
  this.age = age;   // 속성
}

// 메서드 추가
Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};

// 객체 생성
const person1 = new Person("David", 30);
const person2 = new Person("Sean", 26);

person1.greet(); // "Hello, my name is David and I am 30 years old."
person2.greet(); // "Hello, my name is Sean and I am 26 years old."

2. 클래스(Class)

  • ES6에서 도입된 클래스 문법은 객체 지향 프로그래밍을 더욱 직관적으로 구현할 수 있게 해준다.
  • 문법적 설탕(Syntax Sugar): 기존의 생성자 함수 및 프로토타입 기반 상속을 더 쉽게 사용할 수 있도록 해준다.
  • constructor 메서드 : 클래스 내에서 객체의 초기 상태를 설정하는 역할
  • 확장: extends 키워드를 사용하여 기존의 클래스를 확장할 수 있다.
class Person {
  constructor(name, age) {
    this.name = name; // 속성
    this.age = age;   // 속성
  }

  greet() { // 메서드
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

class Student extends Person {
  greet() { // 메서드
    console.log(`Hello, my name is ${this.name} and I am student!`);
  }
}

// 객체 생성
const person = new Person("David", 30);
const student = new Student("Sean", 26);

person.greet(); // "Hello, my name is David and I am 30 years old."
student.greet(); // "Hello, my name is Sean and I am student!"

3. Object.create()

  • 주어진 프로토타입 객체와 프로퍼티로 새 객체를 생성하는데 사용된다.
  • 생성할 객체의 프로토타입을 직접 설정
  • 두 번째 인자로 객체의 프로퍼티를 추가할 수 있다.
const animal = {
  speak() {
    console.log("Animal makes a sound.");
  }
};

// animal을 프로토타입으로 가지는 dog 객체 생성
const dog = Object.create(animal);
dog.speak = function() {
  console.log("Dog barks.");
};

// 메서드 호출
dog.speak(); // "Dog barks."
animal.speak(); // "Animal makes a sound."
profile
어제보다 더 나은

0개의 댓글