can anyone explain how this below works?
var MYAPP = {};
MYAPP.namespace = function(name){
var parts = name.split('.');
var current = MYAPP;
for (var i in parts) {
if (!current[parts[i]]) {
current[parts[i]] = {};
}
// shouldn't this line override the MYAPP object with all it's properties?
current = current[parts[i]];
}
}
currentis first assigned a reference toMYAPP, after that, within the loop, for every part of the Array fromname.splitit is subsequently assigned a reference to the freshly made property ofMYAPP. So nothing is overwritten, because it’s all references.in words for example if you execute
MYAPP.namespace(foo.bar)this happens:currentpoints toMYAPPcurrent /*is ref to MYAPP*/ .foodoesn’t exist, createMYAPP.foocurrentpoint toMYAPP.foocurrent /*is now ref to MYAPP.foo*/ .bardoesn’t exist create itMYAPPcontains:MYAPP.fooMYAPP.foo.barMYAPPasMYAPP.namespace(foo.bar)using an object literal, you would writevar MYAPP = { foo: { bar: {} }