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

The simplest implementation of creating a namespace in JavaScript_javascript skills

WBOY
Release: 2016-05-16 19:07:15
Original
1108 people have browsed it

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

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template