모듈패턴 Ⅰ


이번 포스트 부터는 자바스크립트에서의 모듈패턴에 대해 알아 보도록 하겠습니다.

우선 생성자 함수 모듈패턴의 기본 구조인 "객체 생성"과 관련된 내용에 대해서는 이전 포스트를 참고 하시길 바랍니다.

 

이번 포스트에서는 모듈패턴에 관한 내용만 설명해 드리도록 하겠습니다.

 

먼저 생성자 함수를 사용하여 객체를 생성하면 인스턴스 맴버 와 프로토타입 맴버라는 그룹을
가지게 됩니다.

 

먼저 인스턴스 맴버에 대해 설명하면, 기본 구조는 생성된 빈 객체(this)에 포함되는 맴버 그룹이며, 각 객체 생성 시마다 새로운 맴버그룹이 생성(맴버 초기화)됩니다.

 

프로토타입 맴버는 함수객체 속성인 "prototype" 객체속성을 사용하여 생성할 수 있는 맴버 그룹이며, 인스턴스 맴버와는 달리 함수 생성 시에만 생성(맴버 초기화)됩니다.

 

이와 같은 이유로 인스턴스는 맴버는 각 객체에 종속된 맴버를 가져야 할 때 사용되며, 프로토타입 맴버는 그 종속된 맴버들을 재 사용하기 위한 메소드들을 포함합니다.

 

또한, 이렇게 작성하는 것이 모듈패턴에 대한 최적화 문법이기도 합니다.


  1. function constructor_fn()
  2. {
  3.     this.instance_memeber1 = 'instance_memeber1';
  4.     this.instance_memeber2 = 'instance_memeber2';
  5. };
  6.  
  7. constructor_fn.prototype.prototype_memeber1 = function()
  8. {
  9.     return this.instance_memeber1;
  10. };
  11.  
  12. constructor_fn.prototype.prototype_memeber2 = function()
  13. {
  14.     // 함수 내부의 "this" 는 자신을 호출한 객체가 되며, 또 객체로 인한 호출이 아닌 경우 window 전역객체가 된다.
  15.  
  16.     // 여기서 "this"는 "constructor_fn.prototype" 객체속성이 된다.
  17.     if (this === constructor_fn.prototype){
  18.         return 'constructor_fn.prototype';
  19.         // true
  20.     };
  21.        
  22.     // 여기서 "this"는 "constructor_fn.prototype" 객체속성이 된다.
  23.     if (this === obj){
  24.         return this.instance_memeber2;
  25.     };
  26. };
  27.  
  28. // constructor_fn.prototype 객체 속성으로 호출한다.
  29. alert(constructor_fn.prototype.prototype_memeber2()); // constructor_fn.prototype
  30.  
  31.  
  32. var obj = new constructor_fn();
  33. // 객체의 인스턴스 맴버에 접근한다.
  34. alert(obj.instance_memeber1); // instance_memeber1
  35. // 객체의 프로토타입 맴버에 접근한다.
  36. alert(obj.prototype_memeber2()); // instance_memeber2
  37.  
  38.  
  39. // 즉시 실행 함수 패턴을 응용한 생성자 함수 모듈패턴
  40. // 일단은 이런식의 구현이 가능하다는 것만 알아두도록 하자!!!
  41. var constructor_fn = (function(doc, win){
  42.     return (function()
  43.     {      
  44.         function init(){           
  45.             this.instance_memeber1 = 'instance_memeber1';
  46.             this.instance_memeber2 = 'instance_memeber2';
  47.         };
  48.  
  49.         init.prototype = {
  50.             prototype_memeber1: function(){
  51.                 return this.instance_memeber1;
  52.             },
  53.             prototype_memeber2: function(){
  54.                 return this.instance_memeber2;
  55.             }
  56.         };
  57.  
  58.         return new init();
  59.     })();
  60. })(document, window);
  61.  
  62. alert(constructor_fn.prototype_memeber1()); // instance_memeber1
  63. alert(constructor_fn.prototype_memeber2()); // instance_memeber2