티스토리 뷰

728x90
반응형

Javascript에서 객체 지향적으로 개발 할 수 있게 해주는 것이 프로토타입(Prototype). 일반적으로 일반 개발자들은 프로토타입(Prototype)을 알지 못해도 화면을 개발 할 수 있어서 제대로 인지하지 못하고 있을 수도 있습니다. 하지만 알고 개발하는 것은 중요하기 때문에 정리해보았습니다.

 

* Prototype

Java에는 Class를 기반으로 인스턴스를 생성하여 객체를 사용하죠. Javascript에서는 function을 통해 클래스와 비슷하게 개발할 수 있습니다.  function을 new를 통해 변수에 담아보겟습니다.

 

function Fruit() {
	this.type= "과일";
    this.name; 
}

var melon = new Fruit();
var apple = new Fruit();
melon.name = "메론";
apple.name = "사과";

console.log(melon.type) // -> 과일
console.log(melon.name) // -> 메론

console.log(apple.type) // -> 과일
console.log(apple.name) // -> 사과

new를 통해 객체를 만들면 메모리에 각각 type, name이 담겨 총 4개 할당되겠죠.

하지만 공통적인 값인 type을 메모리에 할당 될 필요가 없기 때문에 메모리 낭비죠. 100개의 객체를 생성하면 100개가 더 생성되기 때문이죠.

이때 프로토타입(Prototype)을 이용해서 해결합니다

 

function Fruit() {
    this.name; 
}

Fruit.prototype.type = "과일";

var melon = new fruit();
var apple = new fruit();
melon.name = "메론";
apple.name = "사과";

console.log(melon.type) // -> 과일
console.log(melon.name) // -> 메론

console.log(apple.type) // -> 과일
console.log(apple.name) // -> 사과

melon과 apple을 생성할때 참조한 프로토타입인 Fruit에는 prototype 프로퍼티가 있습니다.

그래서 Fruit.prototype을 통해 공유하여 사용할 수 있죠.

 

이를 통해서 List를 구현해보겠습니다.

function List() {
   this.elements = {};
   this.idx = 0;
   this.length = 0;
}

List.prototype.add = function(element) {
   this.length++;
   this.elements[this.idx++] = element;
};

List.prototype.get = function(idx) {
   return this.elements[idx];
};

List.prototype.find = function(element) {
	 for(var i=0; i<this.length; i++){
          if(this.elements[i] === element){
                return i;
          }
      }
      return -1;
};

 

 

참고

medium.com/@bluesh55/javascript-prototype-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0-f8e67c286b67

www.nextree.co.kr/p7323/

728x90
반응형
250x250
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함