객체 상속을 이용한 객체유효범위를 생성하는 샌드박스 만들기.


자바스크립트 객체 상속(얕은 복사)을 이용하여 callback 함수 내부에서는 새롭게 할당(배열 인자값)된 객체 만을 사용할 수 있습니다.

공개 메서드(생성자 함수)에 이 패턴을 적용하여, 타 모듈에 대한 접근 권한을 둘 수 있습니다.

  1. var Sendbox = (function (doc, win) {
  2.     return function (opt, callback) {
  3.  
  4.         var parent = {};
  5.  
  6.         function init() {
  7.  
  8.             this.module = null;
  9.             this.boxs = [];
  10.  
  11.             marge.call(this, opt);
  12.  
  13.             var module = this.module
  14.               , boxs = this.boxs;
  15.  
  16.             if (boxs) {
  17.                 var hasOwnProperty = Object.prototype.hasOwnProperty;
  18.                 if (boxs.constructor === Array) {
  19.                     for (var i = 0, length = boxs.length; i < length; i++) {
  20.                         if (hasOwnProperty.call(module, boxs[i])) {
  21.                             parent[boxs[i]] = module[boxs[i]];
  22.                         }
  23.                     }
  24.                 }
  25.                 else if (boxs.constructor === String && boxs === '*') {
  26.                     for (var n in module) {
  27.                         if (hasOwnProperty.call(module, n)) {
  28.                             parent[n] = module[n];
  29.                         }
  30.                     }
  31.                 }
  32.             }
  33.  
  34.  
  35.             if (typeof callback === 'function') {
  36.                 callback.call(null, parent);
  37.             }
  38.  
  39.         };
  40.  
  41.         return new init();
  42.     };
  43.  
  44.     function marge() {
  45.  
  46.         var target = this
  47.           , opts = []
  48.           , src = null
  49.           , copy = null;
  50.  
  51.         for (var i = 0, length = arguments.length; i < length; i++) {
  52.  
  53.             opts = arguments[i];
  54.  
  55.             for (var n in opts) {
  56.  
  57.                 src = target[n];
  58.                 copy = opts[n];
  59.                 target[n] = copy;
  60.             }
  61.         }
  62.  
  63.         return target;
  64.     }
  65. })(document, window);
  66.  
  67.  
  68.  
  69. Sendbox({
  70.     module: modules,
  71.     boxs: ['module1', 'module2']
  72. }, function (box) {
  73.     for (var n in box) {
  74.         alert(n); // module1 module2
  75.     }
  76. });



모듈패턴 Ⅱ


이전 포스트에서 설명드렸던 모듈패턴에 대해 이번 포스트에서는 좀더 다향한 패턴으로 작성해 보도록 하겠습니다.


  1. // 객체 리터널을 사용하여 작성하는 패턴입니다.
  2. var constructor_fn = (function(doc, win){
  3.     // 객체 리터널 형식을 사용하는 작성법
  4.    
  5.     var x = 0
  6.       , y = 0;
  7.  
  8.     return {
  9.         getX: function(){
  10.             return x;
  11.         },
  12.         getXfn: function(){
  13.             return this.getX;
  14.         }
  15.     };
  16.  
  17. })(document, window);
  18.  
  19. // 외부에 노출된 getX 메소드를 변경시키면 메소드 원본이 변경되었으므로 더이상 사용할수 없게 되었습니다.
  20. constructor_fn.getX = null;
  21. alert(constructor_fn.getXfn()); // null
  22.  
  23.  
  24.  
  25.  
  26. // 이번 패턴은 따로 비공개 메서드를 두어 공개할 메서드만 골라서 노출시키는 패턴입니다.
  27. var constructor_fn = (function(doc, win){
  28.     // 객체 리터널 형식을 사용하는 작성법
  29.    
  30.     var x = 0
  31.       , y = 0;
  32.    
  33.     // 비공개 메서드 
  34.     function getX(){   
  35.         return x;
  36.     };
  37.  
  38.     function getY(){
  39.         return y;
  40.     };
  41.  
  42.     function setX(x){
  43.         x = x;
  44.     };
  45.  
  46.     function setY(y){
  47.         y = y;
  48.     };
  49.  
  50.  
  51.     return {
  52.         getX: getX,
  53.         getX1: getX,
  54.         getY: getY
  55.     };
  56.  
  57. })(document, window);
  58.  
  59.  
  60. constructor_fn.getX = null;
  61. // 이전처럼 외부에 노출된 getX 메서드를 변경 하여도 메서드 원본이 비공개 함수로 정의되어 있으므로
  62. // getX 메소드는 공개된 메서드인 getX1를 호출하여도 잘 돌아가게 되는 것입니다.
  63. alert(constructor_fn.getX); // null
  64. alert(constructor_fn.getX1); // function(){ ; }

모듈패턴 Ⅰ


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

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

 

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

 

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

 

먼저 인스턴스 맴버에 대해 설명하면, 기본 구조는 생성된 빈 객체(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
prev 1 ··· 47 48 49 50 51 52 53 ··· 56 next