The simplest implementation _javascript techniques for JavaScript to create namespaces (namespace)

Source: Internet
Author: User
Tags eval
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>
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.