实例:
var myApp = myApp || {}; myApp.namespace = function(ns_string){ var parts = ns_string.split('.'),//["name", "jim", "son", "name", "tom"] parent = this,//最关键的一部,parent已经和myApp搭上关系一直链接下去 i; /* 如果首个字符串‘myApp’,就把数组‘myApp’去掉 */ if (parts[0] === 'myApp') { parts = parts.slice(1); } for (i=0;i<parts.length ;i++ ) { /* 如果parent对象的parts[i]为 undefined,parent[parts[i]]赋为对象 */ if (typeof parent[parts[i]] === 'undefined') { parent[parts[i]] = {}; //console.log( parent ); } parent = parent[parts[i]]; } return parent; } myApp.namespace('name1.jim1.son1'); myApp.namespace('name1.jim1.son3.tom3.son4'); myApp.namespace('name2.jim2.son2'); console.log( myApp );
解释:
[name,jim,son]
myApp => [ 对象1 ]
parent = myApp //parent是为MyApp 添加的子元素的介质
parent => [ 对象1 ]
当i=0时
parent[name] === undefined true
parent.name = {} => [ 对象2 ]
parent = parent.name;[ 对象2 ] 此时左侧parent是[对象2 ]
当i=1时
parent[jim] === undefined true 此时的左侧parent是[对象2 ]
parent.jim = {} => [对象3]
parent = parent.jim; 此时的左侧的parent是[对象3]
当i=2时
parent[son] === undefined true 此时的左侧parent是[对象3]
parent.son = {} => [对象4]
parent = parent.son; 此时左侧parent是[对象4]
当i=3时
return parent; [对象4]