웹개발/JavaScript

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

튼튼발자 2024. 7. 18. 10:19
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