I saw a namespace method when I stripped Baidu's listening player engine a few days ago and thought it was novel. Of course, it was just for myself that I was just getting started with js, before the experience was quite simple, I saw Netease or Sina or another website. I also used something like this. At that time, JavaScript was just a cool level and I was scared on the spot.
But this time, I plan to analyze it myself and I will not be confused when I see it later.
The Code is as follows:
// Call example: bradio. namespace ("bradio. lang. array ");
// The following is the source code compiled by Baidu. the variables are a, B, c, d... And I will re-write a standard point.
// Now, start the analysis.
Bradio. namespace = function () {// create a namespace
Var a = arguments, // ["bradio. lang. array"]
B = null, // used to store the upper-level object
C, d, e, f; // c indicates the counter, d indicates the counter of the inner loop, e indicates the namespace array after splitting, and f indicates the length of the arguments parameter.
C = 0;
For (f = a. length; c <f; c ++ ){
E = ("" + a [c]). split ("."); // split the namespace. After the split, ["bradio", "lang", "array"]
B = bradio; // basic object. Add a namespace based on this object.
For (d = "bradio" = e [0]? 1: 0; d <e. length; d ++) // if the first is bradio, the second starts traversing ["bradio", "lang", "array"]
B [e [d] = B [e [d] | {}, B = B [e [d]
// Actually equivalent
// B [e [d] = B [e [d] | {}// if the current object has been operated, use the current object. If it does not exist, assign a null object.
// B = B [e [d] // overwrite B with a word object. The next loop adds a namespace based on the sub-object.
}
Return B // return the last object
};
The following are the versions that can be understood.
The Code is as follows:
// Bradio. namespace ("bradio. lang. array ");
Bradio. namespace = function () {// create a namespace
Var args = arguments,
Parent = null,
Arr, I, j, len;
For (I = 0, len = args. length; I <len; I ++ ){
Arr = ("" + args [I]). split (".");
Parent = bradio;
For (j = "bradio" = arr [0]? 1: 0; j <arr. length; j ++ ){
Parent [arr [j] = parent [arr [j] || {};
Parent = parent [arr [j];
}
}
Return parent;
}
Of course, it's just my understanding. If it's not right, please help me to point it out so as not to mislead everyone.