I saw that NetEase or Sina or some other website used something similar to this. At that time, my level of js was only a drop in the bucket, and I was shocked on the spot.
But this time, I plan to analyze it myself so that I won’t be confused when I see it in the future.
//Calling example: bradio.namespace("bradio. lang.array");
//The following is the source code compiled by Baidu. The variables are all a, b, c, d... I will re-write a specification point later.
//Okay, let’s start analyzing
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 is the counter, d is the counter of the inner loop, e is the split namespace array, and f is the arguments parameter length
c = 0;
for (f = a.length; c < f; c ) {
e = ("" a[c]).split("."); //Split Divide namespaces, after splitting ["bradio", "lang", "array"]
b = bradio; //Basic object, add namespace based on this object
for (d = "bradio" == e[0] ? 1 : 0; d < e.length; d ) //If the first one is bradio, start traversing ["bradio","lang","array"]
b[e[d]] = b[e[d]] || {}, b = b[e[d]]
b = b[e[d]] || {} //If the current object has been operated on, use the current object. If it does not exist, assign an empty object
//b = b[e[d]] //Cover with word object b. The next loop adds a namespace based on the sub-object
}
return b//Returns the last layer of objects
};
The following is organized, you can see Understand the version
//bradio.namespace("bradio. lang.array");
bradio.namespace = function () { //Create 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] ] || {};
If something is not quite right, please help me point it out so as not to mislead everyone.