This is the code I get, but I don’t know this two lines means:
o[arr[i]] = o[arr[i]] || {};
o = o[arr[i]];
Full code:
var GLOBAL={};
GLOBAL.namespace=function(str){
var arr = str.split("."), o=GLOBAL;
for(i=(arr[0]=="GLOBAL") ? 1 : 0; i<arr.length; i++){
o[arr[i]] = o[arr[i]] || {};
o = o[arr[i]];
}
};
GLOBAL.namespace("A.Dog");
// GLOBAL.A = {};
// GLOBAL.A.Dog = {};
GLOBAL.A.Dog.name = "diudiu";
alert(GLOBAL.A.Dog.name)
Break it down step-by-step to make is clearer:
is the same as:
is the same as:
The pattern
A = B || DEFAULT_VALUEis an idiom which uses the short-circuiting nature of the||operator. In javascript, the||operator does not returntrueorfalsebut instead it returns the first non-false value orfalse. So if the first variable is not falsy it evaluates to the value of the first variable otherwise it evaluates to the value of the second variable.