2023-04-05 14:41:53

Prototype 

프로토타입이란 객체의 원형을 말하며 자바스크립트에선 모든 객체가 프로토타입을 가지며 상속과 비슷한 개념으로 다른 객체의 속성을 상속 받을 수 있는 객체를 말합니다.

 

 

Prototype 문법 이해하기

  • 아래의 문법은 객체에 새 속성을 추가하여 값을 출력한 코드로 speed가 10이 증가하는 함수로 Car2가 생성됬지만 출력결과는 170
  • 객체의 새 속성은 추가 할 수 있지만 객체의 원형은 바뀌지 않는다.
function Car2(m, c, s) {
  this.model = m;
  this.color = c;
  this.speed = s;
  // 속도를 올리고 올린 속도의 값을 반환
  this.speedUP = function () {
    this.speed += 10;
    return this.speed;
  };
}

let temp3 = new Car2("기아", "파랑", 150);
// battery 키 true 값 추가
temp3.battery = true;
// 원형은 10이 올라가지만 20을 올라가는 함수 작성
// 객체에 새 속성을 추가 할 수 있지만 원형에는 추가 할 수 없음
temp3.speedUP = function () {
  this.speed += 20;
  return this.speed;
};

console.log(temp3);
temp3.speedUP();
console.log(temp3);

객체의 원형에 속도는 +10이기 때문에 160이지만 함수를 추가하여 새 속성을 할당하여 speed가 170로 출력

 

 

Prototype 기본 문법

  • 객체명.prototype.메소드 = function(){}
  • 생성자 함수에 메소드를 별도로 정의하지 않고 생성자 외부에 별도의 메소드를 정의해서 사용하는 방법
  • 생성자에 의해 생성된 모든 객체는 생성자 함수의 모든 속성과 메소드를 상속
  • 상속 받은 속성과 메소드를 메모리에 저장하고 동일한 메소드는 메모리에 중복 저장을 피함
function Car3(m, c, s) {
  this.model = m;
  this.color = c;
  this.speed = s;
}

Car3.prototype.speedUP = function () {
  this.speed += 20;
  return this.speed;
};

Car3.prototype.speedDown = function () {
  this.speed -= 20;
  return this.speed;
};

let temp4 = new Car3("대우", "하얀", 100);
let temp5 = new Car3("쌍용", "하얀", 100);

console.log(temp4.speedUP());

 

function Car3(m, c, s) {
  this.model = m;
  this.color = c;
  this.speed = s;
}

temp4.stop = function () {
  this.speed = 0;
  return this.speed;
};

// temp4.stop()의 출력값을 제대로 나오지만 temp5.stop()은 에러
console.log(temp4.stop());
// console.log(temp5.stop());

// 생성자 함수로 만든 객체들에게 전부 메소드를 추가해 주어야 할때
// 프로토 타입으로 원형에 메소드 추가

Car3.prototype.stop = function () {
  this.speed = 0;
  return this.speed;
};

console.log(temp4.stop());
console.log(temp5.stop());

728x90