Knowledge/javascript

javascript 객체 리터럴 패턴과 생성자 패턴, prototype

TakeKnowledge 2019. 9. 9. 23:10
반응형

객체 리터럴 패턴을 활용하면 javscript 코드를 비슷한 기능끼리 묶을 수 있습니다.

 

예를 들어 promotion과 관련된 기능만을

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var promotionObj = {
        // 프로모션 템플릿 붙일 타겟
        imageTarget : document.querySelector(".visual_img"),
        // 프로모션 이미지 템플릿
        imageTemplate : document.querySelector("#imageTemplate").innerText,
        // 이미지 세팅
        setImage : function(productDetail){
            var imageBindTemplate = Handlebars.compile(this.imageTemplate);
            
            var resultHtml = '';
            resultHtml += imageBindTemplate(productDetail);
            
            // ticketBox에 BindTemplate 세팅
            this.imageTarget.innerHTML = resultHtml;
        }
}

이런 식으로 모아서 사용할 수 있는데 이 때의 imageTarget이나 imageTemplate은 고정이다. 

 

즉 객체 리터럴 패턴으로 구현하면

비슷한 기능을 하지만 대상은 다른 무언가를 구현할 때는 똑같은 코드를 대상만 바꿔 또 작성해야 한다는 얘기.

 

이런 단점을 보완할 수 있는데 생성자 패턴이다. 이는 이렇게 사용할 수 있다

 

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
32
33
 
    function promotionObj(imageTarget, imageTemplate) {
    
        // 프로모션 템플릿 붙일 타겟
        this.imageTarget = imageTarget;
        // 프로모션 이미지 템플릿
        this.imageTemplate = imageTemplate;
        // 뒤로 가기 버튼 클릭 이벤트 등록
        // 이미지 세팅
        this.setImage = function(productDetail){
            var imageBindTemplate = Handlebars.compile(this.imageTemplate);
            
            var resultHtml = '';
            resultHtml += imageBindTemplate(productDetail);
            
            // ticketBox에 BindTemplate 세팅
            this.imageTarget.innerHTML = resultHtml;
        }
 
 
    // 다른 타겟으로 promotion1 객체 생성    
    var promotion1 = new promotionObj('다른 타켓''다른 템플릿');
    // 또다른 타겟으로 promotion2 객체 생성
    var promotion2 = new promotionObj('또다른 타켓''또다른 템플릿');
 
    // 다른 타겟에 이미지 세팅
    promotion1.setImage();
 
    // 또다른 타겟에 이미지 
    promotion2.setImaget();
        
}
 

 

 

이렇게 객체를 함수 형태로 선언해서 클래스를 객체로 생성하듯 

다른 파라미터를 넣어주면 코드의 중복을 막을 수 있다.

 

다만 보다시피 여기서도 코드의 불필요한 중복은 있다.

바로 setImage 부분인데 완전히 동일한 코드가 객체를 생성할 때 마다 메모리를 차지하는 비효율을 야기한다

 

그러나 이도 역시 극복가능하다. prototype을 활용하면 되는데 

 

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
32
33
34
35
36
37
38
39
 
    function promotionObj(imageTarget, imageTemplate) {
    
        // 프로모션 템플릿 붙일 타겟
        this.imageTarget = imageTarget;
        // 프로모션 이미지 템플릿
        this.imageTemplate = imageTemplate;
        // 뒤로 가기 버튼 클릭 이벤트 등록
        // 이미지 세팅
    }
 
    promotionObj.prototype = {
        
        // 이미지 세팅
        setImage : function(productDetail){
            var imageBindTemplate = Handlebars.compile(this.imageTemplate);
            
            var resultHtml = '';
            resultHtml += imageBindTemplate(productDetail);
            
            // ticketBox에 BindTemplate 세팅
            this.imageTarget.innerHTML = resultHtml;
        }
 
    }
 
    // 다른 타겟으로 promotion1 객체 생성    
    var promotion1 = new promotionObj('다른 타켓''다른 템플릿');
    // 또다른 타겟으로 promotion2 객체 생성
    var promotion2 = new promotionObj('또다른 타켓''또다른 템플릿');
 
    // 다른 타겟에 이미지 세팅
    promotion1.setImage();
 
    // 또다른 타겟에 이미지 세팅
    promotion2.setImaget();
        
}
 

 

이렇게 prototype을 선언하고 그 안에 함수를 집어넣어주면 

굳이 객체가 생성할 때마다 메모리를 할당하지 않고도

promotionObj를 구현한 객체라면 어디서든 동일한

(promotion1.setImage() === promotion2.setImage() 를 하면 true가 나온다 ) setImage를 사용할 수 있다. 

 

반응형