프로토타입과 클래스

dice0314·2023년 5월 11일
0

프로토타입

  • 프로토타입은 객체 지향 프로그래밍에서 원형 객체를 의미한다.
  • 프로토타입은 다른 객체에게 공유할 속성과 메서드를 제공하여 기반이 되어줄 객체이다.
  • 새로운 객체는 프로토타입 객체에 정의된 속성과 메서드를 상속받아 사용할 수 있다
  • 프로토타입으로 객체 간에 상속 관계를 구현하여 코드의 재사용성과 유연성을 높인다.
  • JavaScript에서는 모든 객체는 프로토타입을 가진다.

class Car {
  constructor(brand, model, color) {
    this.brand = brand;
    this.model = model;
    this.color = color;
    this.speed = 0;
  }
  accelerate() {this.speed += 10;}
  brake() {this.speed -= 10;}
}
const newCar = new Car("Hyundai", "Sonata", "Black");

📌 .__proto__

'.__proto__'는 객체의 프로토타입에 접근하기 위한 속성이다.

  • 모든 JavaScript 객체는 .__proto__ 속성을 가지고 있으며, 해당 객체의 프로토타입 객체를 가리킨다.
  • 객체는 프로토타입 체인을 따라 상위 프로토타입으로 연결되어 있는 속성과 메서드에 접근할 수 있다.
newCar.__proto__;

위의 결과

Car {
  constructor(brand, model, color) {
    this.brand = brand;
    this.model = model;
    this.color = color;
    this.speed = 0;
  }
  accelerate() {
    this.speed += 10;
  }
  brake() {
    this.speed -= 10;
  }
}

📌 .prototype

'.prototype'은 함수 객체에만 존재하는 속성이다.

  • 함수를 정의할 때 해당 함수의 프로토타입 객체를 가리킨다.
  • 함수로 생성된 객체들이 상속받을 속성과 메서드를 포함한다.
Car.prototype;

위의 결과

Car {
  constructor(brand, model, color) {
    this.brand = brand;
    this.model = model;
    this.color = color;
    this.speed = 0;
  }
  accelerate() {
    this.speed += 10;
  }
  brake() {
    this.speed -= 10;
  }
}

클래스, 인스턴스, 프로토타입의 관계

세가지의 관계는 다음과 같이 생각할 수 있다.

  • 클래스 : 자동차의 완제품(인스턴스)를 만들기 위해 기초가 되는 뼈대

  • 인스턴스 : 뼈대(클래스)를 기반으로 만들어진 완성품 자동차

  • 프로토타입 : 완성품 자동차(인스턴스)의 뼈대(클래스)에 저장된 속성이나 메서드를 찾는 경로

profile
정리노트

0개의 댓글