two depth 이상의 빈 JS 객체를 생성해보자
BKJang opened this issue · comments
JangBongKi commented
❗️ How did I encounter this issue?
FormData
를 Server의 api 규격에 맞추기 위해서 빈 객체를 만들어야할 경우가 있는데 이 때, 매번 빈 객체의 NPE체크를 진행해줘야하는 불편함이 존재.
🔨 What have I tried? How did you finally solve it?
var MYAPP = MYAPP || {};
MYAPP.namespace = function(ns_string) {
var parts = ns_string.split('.'),
parent = MYAPP,
i;
if (parts[0] === "MYAPP") {
parts = parts.slice(1);
}
for (i = 0; i < parts.length; i += 1) {
if (typeof parent[parts[i]] === "undefined") {
parent[parts[i]] = {};
}
// 참조를 변경한다. ( parent -> MYAPP 에서 parent -> MYAPP.parts[i]로 변경)
parent = parent[parts[i]];
}
return parent;
}
MYAPP.namespace("MYAPP.modules.module2");
var module2 = MYAPP.namespace("MYAPP.modules.module2");
module2 === MYAPP.modules.module2; // true