Home  >  Article  >  Web Front-end  >  The simplest implementation of creating a namespace in JavaScript_javascript skills

The simplest implementation of creating a namespace in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 19:07:151032browse

I recently looked at the Ext source code and saw how it implements the namespace function:

Ext NameSpace implementation code:

Copy code The code is as follows:

namespace : function(){
var a=arguments, o=null, i, j, d, rt;
for (i=0 ; i d=a[i].split(".");
rt = d[0];
eval('if (typeof ' rt ' = = "undefined"){' rt ' = {};} o = ' rt ';');
for (j=1; j o[d[j] ]=o[d[j]] || {}; 🎜>


I like the simplest programming (this is often not a good habit. The simpler the program is, the harder it is to understand), so I want to solve this problem in a shorter way.
After trying for nearly half an hour, I wrote the following implementation. Basically, all the situations that should be considered are considered, at least it will not overwrite the functions that already exist on the page.
The implementation code is as follows:




Copy code

The code is as follows:function namespace (ns){ if(typeof(ns)!="string")return; ns=ns.split("."); var o,ni;
for(var i =0,len=ns.length;i try{o=(o?(o[ni]=o[ni]||{}):( eval(ni "=" ni "||{}")))}catch(e){o=eval(ni "={}")}
      } 




You can save the following code for testing:

Test code:




Copy code

Previous article:The difference and connection between the two caused by undefined==null Page 1/3_javascript skillsNext article:The difference and connection between the two caused by undefined==null Page 1/3_javascript skills

Related articles

See more