PDA

View Full Version : Ext.namespace



Wylde
4 Aug 2007, 2:28 PM
1. namespace : function(){
2. var a=arguments, o=null, i, j, d, rt;
3. for (i=0; i<a.length; ++i) {
4. d=a[i].split(".");
5. rt = d[0];
6. eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
7. for (j=1; j<d.length; ++j) {
8. o[d[j]]=o[d[j]] || {};
9. o=o[d[j]];
10. }
11. }
12. },

In this function, why in line 9 the var 'o' is reassigned with o[d[j]] ? if you remove line 9 ,nothing change in the normal workflow.

Suppose Ext.namespace("Ext","Ext.utils");

in the 1st cicle, only the first for it's executed, so o = Ext object.
in the 2nd cicle, the 2nd for it's executed, so o["utils"] = {} ....ok
but in the next line ... o = o["utils"] ?? if so, Ext object it's totally erased... or not ?


thx for reading :)

jack.slocum
4 Aug 2007, 5:15 PM
Since it is used pretty heavily, I would say it is highly unlikely it will blow away the Ext object. ;)

rtannert2
5 Aug 2007, 4:06 AM
In line 9 o is set equal to the namespace that was just verified to exist or created if it didn't exist, to serve as the starting point for the next iteration of the inner loop. In the case of 'Ext.util' the inner loop is executed only once so line 9 doesn't really do anything helpful. Let's take a slightly more complicated example:


Ext.namespace('Ext.util.Format');

In this example the inner loop will get executed twice. In the first iteration:


for (i=0; i<a.length; ++i) { // evaluate 'Ext.util.Format'
d=a[i].split("."); // d = ['Ext', 'util', 'Format']
rt = d[0]; // rt = 'Ext'
eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
// Ext is created only if it doesn't exist, then o is set = Ext
for (j=1; j<d.length; ++j) { // first pass of inner loop: o[d[j]] = Ext['util']
o[d[j]]=o[d[j]] || {}; // Ext['util'] is created if it doesn't exist
o=o[d[j]]; // o is set = Ext['util'], which is the same as Ext.util
}
}



Then in the second iteration:


for (j=1; j<d.length; ++j) { // second pass of inner loop: o[d[j]] = Ext.util['Format']
o[d[j]]=o[d[j]] || {}; // Ext.util['Format'] is created if it doesn't exist
o=o[d[j]]; // o is set = Ext.util['Format'] in case another iteration is needed
}

Make sense?

Wylde
5 Aug 2007, 4:50 AM
thanks! now I 've understood what was wrong !

in the famous line 9 ( o=o[d[j]]; ) o is simply referred (like a sort of pointer) to o[d[j]] !!
i was convinced that o became EQUAL TO a VALUE (in the case of the first cicle a null object {})

i'm saying right or ?

anyway , thanks a lot for the time spent for me!! you have been very illuminant !! :)

rtannert2
5 Aug 2007, 8:59 AM
Yes, you're correct. o is a pointer, or reference, to an object. Glad I could help!