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


자바스크립트 객체 상속(얕은 복사)을 이용하여 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. });