javascript - how to create two different nameSpaces in one same nameSpace avoiding covering the first one? -
i want use 2 string(which dont know content) create 2 namespace.and don
t want create new 1 if namespace exists. here code:
function createnamespace(namespace) { var spacearr = namespace.split("."); var curspace = window; //judge if namespace exists. var i; for(i in spacearr) { curspace = curspace[spacearr[i]]; if(curspace) window.alert("namespace1:" + namespace + "\ncurspace exists:" + curspace + "\ni:" + + "\nspacearr[i]:" + spacearr[i] + "|"); else { curspace = {}; window.alert("namespace1:" + namespace + "\ncurspace not found:" + curspace + "\ni:" + + "\nspacearr[i]:" + spacearr[i] + "|"); break; } } //now curspace must have been created. i++; //window.alert("namespace2:" + namespace + "\ni:" + + "\nspacearr.length:" + spacearr.length); //create namespace for(;i < spacearr.length; i++) { //window.alert("namespace2:" + namespace + "\ni:" + + "\nspacearr.length:" + spacearr.length); if(i == 0) { window[spacearr[i]] = {}; curspace = window[spacearr[i]]; } else { //window.alert("namespace3:" + namespace + "\ncurspace[spacearr[i]]:" + curspace[spacearr[i]]); curspace[spacearr[i]] = {}; curspace = curspace[spacearr[i]]; } } return curspace; }
the problem is,if send"mytest.mynamespace"and"mytest.monanamespace" func,it alert"curspace not found",which should "curspace exists:" when send "mytest.monanamespace" . can`t tell mistakes are,can tell me?
i think algorithm little complex. refactored little , added test , verified worked in console. have written code several times, pretty sure have hit requirements
function createnamespace(namespace) { var spacearr = namespace.split("."); var curspace = window; //judge if namespace exists. var = 0; for(i = 0;i < spacearr.length; i++) { var next = spacearr[i]; console.log(curspace, next); if(curspace[next] == undefined) { curspace[next] = {}; curspace = curspace[next] } else { curspace = curspace[next]; } } return curspace; } createnamespace("mytest.mynamespace"); console.log(mytest.mynamespace); mytest.mynamespace.myname = "leat hakkor"; createnamespace("mytest.monanamespace"); console.log(mytest.monanamespace); console.log(mytest.mynamespace.myname);
Comments
Post a Comment