Recently look at the EXT source code, see its implementation of the namespace function implementation method:
EXT namespace Implementation code:
Copy Code code as follows:
Namespace:function () {
var a=arguments, O=null, I, J, D, RT;
For (i=0 i<a.length; ++i) {
D=a[i].split (".");
RT = D[0];
Eval (' if (typeof ' + rt + ' = = undefined ') {' + rt + ' = {};} o = ' + rt + '; ');
For (j=1 j<d.length; ++j) {
O[D[J]]=O[D[J]] | | {};
O=O[D[J]];
}
}
}
I prefer the minimalist programming (which is often not a good habit, the simpler the program is generally more difficult to understand), so I want to solve this problem in a shorter way.
Tried for nearly half an hour to write down the following implementation, the basic considerations are considered, at least will not overwrite the page already exists function.
The implementation code is as follows:
Copy Code code as follows:
function namespace (ns) {
if (typeof (NS)!= "string") return;
Ns=ns.split (".");
var O,ni;
for (Var i=0,len=ns.length;i<len,ni=ns[i];i++) {
Try{o= (O?) ( o[ni]=o[ni]| | {}):(eval (ni+ = "+ni+" | | {} "))}catch (e) {o=eval (ni+" ={} ")}
}
}
You can save the following code to test:
Test code:
Copy Code code as follows:
<script type= "Text/javascript" >
<!--
function namespace (ns) {
if (typeof (NS)!= "string") return;
Ns=ns.split (".");
var O,ni;
for (Var i=0,len=ns.length;i<len,ni=ns[i];i++) {
Try{o= (O?) ( o[ni]=o[ni]| | {}):(eval (ni+ = "+ni+" | | {} "))}catch (e) {o=eval (ni+" ={} ")}
}
}
function A () {return 5}
Namespace ("a.b");
alert (a);
Alert (A.B)
Namespace ("Test.test.abc")
Test.test.abc.func1=function () {
Alert (' func1 run ')
}
Alert (test.test)
Test.test.abc.func1 ();
-->
</script>