JavaScript函数创建命名空间

时间:2011-12-11 16:52:51

标签: javascript

下面是为模块创建命名空间的脚本,在parent = parent[parts[i]]后我无法理解它是如何工作的,它是如何创建嵌套的?有什么建议吗?

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) {
        // create property if doesn't exist
        if (typeof parent[parts[i]] === "undefined") {
            parent[parts[i]] = {};
        }
        parent = parent[parts[i]];
    }
    return parent;
};

var module2 = MYAPP.namespace('MYAPP.modules.module2');
module2 === MYAPP.modules.module2; // true

2 个答案:

答案 0 :(得分:0)

简单地说,该函数将函数参数(一个完全限定的名称)拆分为其组成部分(用点分隔)。然后,它说,“此对象是否作为当前父项的属性存在?不,将其创建为对象的属性,并使其成为下一个父项。是,设置现有父项作为父对象,并为每个名称重复。“之后,它返回整个对象,您已将其分配给var module2

答案 1 :(得分:0)

这是你不理解的部分:

for (i = 0; i < parts.length; i += 1) {
  // create property if doesn't exist
  if (typeof parent[parts[i]] === "undefined") {
    parent[parts[i]] = {};
  }
  parent = parent[parts[i]];
}


So parent = MYAPP and parts = ['modules', 'module2'];

以下是循环中的内容:

**i = 0** <br />
typeof parent[parts[0]] equals 'undefined' since MYAPP['modules] doesn't exist <br />
MYAPP['modules'] = {} (MYAPP is parent here and parts[0] equals 'modules') <br />
parent = MYAPP['modules'] <br />
**i = 1** <br />
typeof parent[parts[1]] equals 'undefined' since MYAPP['modules]['module2'] doesn't exist <br />
MYAPP['modules']['module2'] = {} <br />
parent = MYAPP['modules']['module2'] <br />
exists the loop since 1 < 1 is false <br />
returns parent, which is MYAPP['modules']['module2'] <br />