객체 상속을 이용한 객체유효범위를 생성하는 샌드박스 만들기.
Javascript 2012. 1. 29. 14:01
자바스크립트 객체 상속(얕은 복사)을 이용하여 callback 함수 내부에서는 새롭게 할당(배열 인자값)된 객체 만을 사용할 수 있습니다.
공개 메서드(생성자 함수)에 이 패턴을 적용하여, 타 모듈에 대한 접근 권한을 둘 수 있습니다.
-
var Sendbox = (function (doc, win) {
-
return function (opt, callback) {
-
-
var parent = {};
-
-
function init() {
-
-
this.module = null;
-
this.boxs = [];
-
-
marge.call(this, opt);
-
-
var module = this.module
-
, boxs = this.boxs;
-
-
if (boxs) {
-
var hasOwnProperty = Object.prototype.hasOwnProperty;
-
if (boxs.constructor === Array) {
-
for (var i = 0, length = boxs.length; i < length; i++) {
-
if (hasOwnProperty.call(module, boxs[i])) {
-
parent[boxs[i]] = module[boxs[i]];
-
}
-
}
-
}
-
else if (boxs.constructor === String && boxs === '*') {
-
for (var n in module) {
-
if (hasOwnProperty.call(module, n)) {
-
parent[n] = module[n];
-
}
-
}
-
}
-
}
-
-
-
if (typeof callback === 'function') {
-
callback.call(null, parent);
-
}
-
-
};
-
-
return new init();
-
};
-
-
function marge() {
-
-
var target = this
-
, opts = []
-
, src = null
-
, copy = null;
-
-
for (var i = 0, length = arguments.length; i < length; i++) {
-
-
opts = arguments[i];
-
-
for (var n in opts) {
-
-
src = target[n];
-
copy = opts[n];
-
target[n] = copy;
-
}
-
}
-
-
return target;
-
}
-
})(document, window);
-
-
-
-
Sendbox({
-
module: modules,
-
boxs: ['module1', 'module2']
-
}, function (box) {
-
for (var n in box) {
-
alert(n); // module1 module2
-
}
-
});