下面是为模块创建名称空间的脚本,在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

===============>>#1 票数:0

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

===============>>#2 票数: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 />

  ask by Aleksey Savitsky translate from so

未解决问题?本站智能推荐:

关注微信公众号