본문 바로가기

2 TYPE의 Prototype 본문

STUDY/Javascript N Jquery

2 TYPE의 Prototype

Publee 2019. 2. 28. 18:11

 프로토타입을 사용하는데에 장점은 ? 


객체지향적이고 상속을 사용한다라는 점과 프로토타입 객체를 사용하면 객체가 프로토타입의 프로퍼티를 상속할 수 있어서 각 객체에 필요한 리소스의 양을 대폭 줄일 수 있다는 장점이 있습니다.


프로토타입의 방식은 2가지로 나뉘게 되는데,

 Classical 방식과  Prototypal 방식이 있습니다.



두가지의 결과는 같지만 차이를 알아봅시다.


먼저  Classical 방식을 보면

function Point(x,y){
  this.x = x;
  this.y = y;
}
 
// 객체 생성
number = new Point(5,5);
number2 = new Point(3,3);
 
// 프로토타입에 메서드를 추가
Point.prototype.add = function(){
  return this.x + this.y;
}   
  
// 프로토타입에 메서드를 추가
Point.prototype.multi = function(){
  return this.x * this.y;
}   

console.log(number.add());  // 10
console.log(number.multi());  // 25

console.log(number2.add());  // 6
console.log(number2.multi());  // 9


그 다음  Prototypal 방식은

var Point = {
  add : function (a, b) {
    return a + b;
  },
  multi : function (a, b) {
    return a * b;
  }
}

var number = Object.create(Point);
var number2 = Object.create(Point);

console.log(number.add(4,4)); //8
console.log(number.multi(4,4)); //16

console.log(number2.add(3,2)); //5
console.log(number2.multi(3,2)); //6


코드를 보면 알 수 있듯이  Prototypal 방식이 좀 더 간결하고 직관적으로 표현이 가능하고,

객체 생성과 동시에 부모객체를 지정하여 코드의 재활용을 간단하게 구현할 수 있습니다.

또, 한 줄로 객체를 생성함과 동시에 부모객체의 속성도 모두 물려받았습니다.

JavaScript에서는 new 연산자와 함수를 통해 생성한 객체를 사용하는  Classical 방식보다  Prototypal 방식을 더 선호합니다.

Comments