JavaScript 객체 지향 - prototype

김민재·2021년 7월 9일
0

prototype

  • 프로토타입이란 객체들이 공통으로 사용하는 속성값을 의미한다. 객체 내 함수(메소드)를 객체 외부로 인출한 함수 원형으로서 객체들은 모두 prototype을 참조한다.

-생성자 함수에 공통적으로 사용하는 메소드 (속성)에 prototype이라는 고유의 속성 값을 지정해줌으로서, 객체를 생성할 때 마다 그 객체는 이미 지정된 prototype에 속한 함수 값을 참조하게 된다.
-많은 객체가 생성되더라도 메소드는 한번만 생성되므로 성능저하, 메모리 낭비를 방지한다.

<script>
function Person(name, f, s, t){
  this.name = name;
  this.first = f;
  this.second = s;
  this.third = t;
  this.sum = function() {
    return this.first+this.second+this.third;
  }
}
const k = new Person('KIM',10,20,30);
k.sum = function(){
  return 'modified :' + (this.first+this.second+this.third); 
}
const m = new Person('MIN',10,10,10);
l.sum = function(){
  return 'modified :' + (this.first+this.second+this.third); 
}
console.log("k.sum()",k.sum());
console.log("m.sum()",m.sum());
</script>

-생성자 안에서 메소드를 만들 경우 생산성이 떨어진다. 왜냐하면 객체를 생성할 때 마다 같은 동작을 하는 메소드로 인해 성능이 저하되고 메모리가 낭비된다.
-따라서 Person 생성자를 사용하여 만든 모든 객체가 공통적으로 사용하는 함수와 속성을 만들기 위한 키워드로 prototype을 사용한다.

<script>
function Person(name, f, s, t){
 this.name = name;
 this.first = f;
 this.second = s;
 this.third = t;
}
Person.prototype.sum = function() {
 return 'prototype :' + (this.first+this.second+this.third);
}
//나머지 m, j 객체가 참조하는 sum 메소드
const k = new Person('KIM',10,20,30);
k.sum = function(){
 return 'this :' +  (this.first+this.second+this.third);
}
//k객체의 sum메소드만 다르게 작동하기 위한
const m = new Person('MIN',10,10,10);
const j = new Person('jae',10,20,10);
console.log("k.sum()",k.sum());
console.log("m.sum()",m.sum());
console.log("j.sum()",j.sum());
</script>
profile
자기 신뢰의 힘을 믿고 실천하는 개발자가 되고자합니다.

0개의 댓글