ProtoType(프로토타입) 그게 뭐죠?

2024. 7. 18. 10:19·웹개발/JavaScript
728x90

오늘은 프로토타입에 대해 알아보자. 프로토타입은 자바스크립트에서 객체들이 서로 기능을 공유할 수 있게 해주는 중요한 개념이야. 잘 이해해보면, 프로그래밍이 훨씬 쉬워질 거야!


생성자 함수와 프로토타입

먼저, 우리는 생성자 함수를 이용해서 여러 개의 객체를 만들 수 있었지? 예를 들어볼게:)

생성자 함수를 모른다면 내가 쓴 글을 한 번 읽어보는 것을 추천할게! -> 읽어보기

function MakeAnimalObject() {
  this.animalName = "곰";
  this.animalType = "고양이";
  this.animalAge = 8;
  this.animalGender = "male";
  this.lastVisit = "2023-08-11";
  this.getLastMedical = function() {
    return this.animalName + "는 " + this.lastVisit + "에 마지막으로 진료받았습니다.";
  }
}

let animal1 = new MakeAnimalObject();
let animal2 = new MakeAnimalObject();

이렇게 하면 animal1과 animal2라는 두 객체가 만들어져. 그런데, 이 두 객체는 서로 같지 않다는 걸 알 수 있어.

console.log(animal1 == animal2); // false
console.log(animal1 === animal2); // false

하지만, 이 두 객체의 프로토타입 객체는 같아.

console.log(animal1.__proto__ == animal2.__proto__); // true
console.log(animal1.__proto__ === animal2.__proto__); // true

프로토타입 객체의 역할

프로토타입 객체는 생성자 함수로 만들어진 모든 객체들이 공통으로 사용할 수 있는 기능을 담고 있어.

예를 들어, 우리가 모든 동물 객체에 공통으로 사용할 수 있는 메서드를 프로토타입에 추가할 수 있어.

MakeAnimalObject.prototype.getName = function() {
  return `이름은 ${this.animalName}입니다.`;
};

console.log(animal1.getName()); // 이름은 곰입니다.
console.log(animal2.getName()); // 이름은 곰입니다.

이렇게 하면, animal1과 animal2 모두 getName 메서드를 사용할 수 있어. 왜냐하면 이 메서드는 프로토타입 객체에 추가되었기 때문이야.


프로토타입을 활용한 동물 병원 진료 기록

프로토타입을 사용하면, 여러 객체들이 공통으로 사용할 수 있는 메서드들을 효율적으로 관리할 수 있어. 예를 들어, 동물 병원의 진료 기록 로직을 구현해볼게.

프로토타입 없이 구현한 예시:

function AnimalMedicalRecord(params) {
  this.animalName = params?.animalName || "no-data";
  this.animalAge = params?.animalAge || "no-data";
  this.animalGender = params?.animalGender || "no-data";
  this.lastMedicalDate = null;
  this.startMedical = function() {
    const startTime = this.getCurrentTime();
    this.lastMedicalDate = startTime;
    console.log(`[${startTime}] 진료가 시작되었습니다.`);
  };
  this.saveMedical = function() {
    const saveData = {
      animalName: this.animalName,
      animalAge: this.animalAge,
      animalGender: this.animalGender,
      lastMedicalDate: this.lastMedicalDate,
    };
    console.log("save 되었습니다.");
    console.log(saveData);
  };
  this.getCurrentTime = function() {
    const date = new Date();
    return `${date.getFullYear()}.${
      date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1
    }.${
      date.getDate() < 10 ? "0" + date.getDate() : date.getDate()
    } ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
  };
}

const client = new AnimalMedicalRecord({ animalName: "곰이", animalAge: 9, animalGender: "male" });
client.startMedical();
client.saveMedical();

 

프로토타입을 사용한 예시:

function AnimalMedicalRecord(params) {
  this.animalName = params?.animalName || "no-data";
  this.animalAge = params?.animalAge || "no-data";
  this.animalGender = params?.animalGender || "no-data";
  this.lastMedicalDate = null;
}

AnimalMedicalRecord.prototype.saveMedical = function() {
  const saveData = {
    animalName: this.animalName,
    animalAge: this.animalAge,
    animalGender: this.animalGender,
    lastMedicalDate: this.lastMedicalDate,
  };
  console.log("아래의 데이터가 save 되었습니다.");
  console.log(saveData);
};

AnimalMedicalRecord.prototype.getCurrentTime = function() {
  const date = new Date();
  return `${date.getFullYear()}.${
    date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1
  }.${
    date.getDate() < 10 ? "0" + date.getDate() : date.getDate()
  } ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
};

AnimalMedicalRecord.prototype.startMedical = function() {
  const startTime = this.getCurrentTime();
  this.lastMedicalDate = startTime;
  console.log(`[${startTime}] 진료가 시작되었습니다.`);
};

const client = new AnimalMedicalRecord({ animalName: "곰이", animalAge: 9, animalGender: "male" });
client.startMedical();
client.saveMedical();

이렇게 하면, AnimalMedicalRecord 객체에서 공통적으로 사용할 수 있는 메서드들을 프로토타입에 추가해서 관리할 수 있어. 이 방식이 더 효율적이고 깔끔하지!


프로토타입은 생성자 함수로 만들어진 모든 객체들이 공통으로 사용할 수 있는 기능들을 담고 있는 특별한 객체야. 프로토타입을 잘 활용하면, 코드가 더 효율적이고 관리하기 쉬워져. 친구들도 프로토타입을 잘 이해하고 활용해보길 바래! 궁금한 점이 있으면 언제든지 물어봐!

728x90

'웹개발 > JavaScript' 카테고리의 다른 글

DOM(Documents Object Model)이 뭐야!?@!??  (0) 2024.07.20
자바스크립트의 함수 선언 및 표현 방법을 알려줄게!  (0) 2024.07.18
생성자 함수란 무엇일까?  (0) 2024.07.18
자바스크립트 자료형 쉽게 이해하기: 기본 자료형부터 참조 자료형까지  (0) 2024.07.17
웹 브라우저 작동 방식: 친구야, 이거 알면 웹 개발이 쉬워져!  (0) 2024.07.15
'웹개발/JavaScript' 카테고리의 다른 글
  • DOM(Documents Object Model)이 뭐야!?@!??
  • 자바스크립트의 함수 선언 및 표현 방법을 알려줄게!
  • 생성자 함수란 무엇일까?
  • 자바스크립트 자료형 쉽게 이해하기: 기본 자료형부터 참조 자료형까지
튼튼발자
튼튼발자
프론트엔드 개발자입니다. 헬스를 가끔해서인지 몸이 튼튼한거 같습니다. 그래서 튼튼한 개발자 => 튼튼발자입니다. 프론트엔드 및 관련 개발 내용 블로그 글로 정리해서 올려둡니다.
    250x250
  • 튼튼발자
    튼튼발자
    튼튼발자
  • 전체
    오늘
    어제
    • 분류 전체보기 (192)
      • 튼튼발자의 끄적끄적 (10)
      • 웹개발 (94)
        • HTML (5)
        • CSS (2)
        • JavaScript (40)
        • TypeScript (5)
        • REACT (22)
        • Next.js (13)
        • GIt (7)
      • 기타 (3)
        • 일상 (3)
      • 프로젝트 (27)
        • Componique: UI 컴포넌트 라이브러리 (18)
        • GitHub Profile Viewer (8)
        • 잇핏 (1)
      • 프론트엔드 개발자로 취업준비 (1)
        • 기술 면접 (7)
        • 코딩 테스트 준비하기 (0)
        • 자기소개서&지원서&이력서 (0)
      • 컴퓨터과학 (12)
        • 운영체제 (6)
        • 알고리즘 (6)
      • 전공 공부 (37)
        • AI(인공지능) (2)
        • 컴퓨터네트워크 (19)
        • 네트워크프로그래밍 (3)
        • SW소프트웨어응용설계 (7)
        • 클라우드컴퓨팅 (3)
        • 웹서비스프로그래밍 (3)
      • PT (0)
      • 취준일기 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    ui컴포넌트
    JS
    코딩
    NextJs
    웹개발
    프로그래밍
    프론트엔드개발
    상태관리
    JavaScript
    프론트엔드
    github
    tailwind
    리액트
    네트워크
    TCP
    componique
    react
    데이터전송
    자바스크립트
    트랜스포트계층
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
튼튼발자
ProtoType(프로토타입) 그게 뭐죠?
상단으로

티스토리툴바