JavaScript函数创建命名空间

JavaScript function creates namespace

本文关键字:命名空间 创建 函数 JavaScript      更新时间:2023-09-26

下面是为模块创建命名空间的脚本,我无法理解它在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

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

这是你不明白的部分:

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 />