简体   繁体   English

JavaScript函数创建名称空间

[英]JavaScript function creates namespace

Below there is the script which create namespace for module, I can't understand how it works after parent = parent[parts[i]] , how does it create nesting? 下面是为模块创建名称空间的脚本,在parent = parent[parts[i]]之后,我不明白它是如何工作的,它如何创建嵌套? Any suggestions? 有什么建议么?

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

Put simply, the function splits the function parameter (a fully qualified name) into its constituent parts (separated by dots). 简而言之,函数将函数参数(完全限定的名称)分成其组成部分(以点分隔)。 Then, it says, "Does this object exist as a property of the current parent? No, create it as a property of the parent object, and make it the next parent. Yes, set the existing one as the parent object, and repeat for each name." 然后,它说:“此对象是否作为当前父对象的属性存在?否,将其创建为父对象的属性,并使其成为下一个父对象。是的,将现有对象设置为父对象,然后重复每个名字。” After that, it returns the whole object, which you have assigned to your var module2 . 之后,它将返回已分配给var module2的整个对象。

This is the part you didn't understand: 这是您不了解的部分:

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'];

Here's what's done in the loop: 在循环中完成以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM