(转)在Js中应用命名空间

本文介绍如何在JavaScript中通过命名空间技术改善代码组织,避免命名冲突,并通过实例展示具体应用。

转载自:http://www.cnblogs.com/anytao/archive/2010/10/22/anytao-devstory-15-use-namespace-in-js.html

Introduction

How to have a better code organization? When your software become bigger and bigger, the code will torture you all the time. So, the smart guy  innovate the Namespace to handle this issue. For example, in .NET world, we define the class in scope of namespace:

 
  
namespace Anytao.Common
{
public class Console
{
public static void Read( string msg)
{
}
}
}

Then, we can use Console as below:

 
  
Anytao.Common.Console.Read( " Hello, world. " );

It will bring the following benefit:

  • Better code organization
  • Avoid naming conflict. For example, If we have another Console in the same assembly, it will cause error without namespace control. Now, we can absolutely separate naming by namespace.
 
  
Anytao.Common.Console.Read( " Hello, world. " );

System.Console.Read();

Namespace in JavaScript

However, there is no language level support in JavaScript. It will cause a lot of problem and mess the process of development. Here is a experience in our project.

 
  
/* Define the NS in imxiqi.js */
var X8JS = {};
X8JS.ns
= function (path) {
var arr = path.split( " . " );
var ns = "" ;
for ( var i = 0 ; i < arr.length; i ++ ) {
if (i > 0 )
ns
+= " . " ;
ns
+= arr[i];
eval(
" if(typeof( " + ns + " ) == 'undefined') " + ns + " = new Object(); " );
}
};
注,上述代码来自互联网)

How to use?

  • Reference the imxiqi.js file in your page head.

<scriptsrc="http://www.cnblogs.com/static/js/imxiqi.js"type="text/javascript"></script>

  • Register the namespace when you use
 
  
X8JS.ns( " XLR8.feed " );
Define the class, variables and others in your namespace
 
  
X8JS.ns( " XLR8.feed " );
X8JS.ns(
" Ethos.common " );

XLR8.feed
=
{
alert:
function (msg) {
alert(msg);
},

load:
function () {
}

};

Ethos.common.copyright
= function BindData(data) {
$(
" #copyright " ).html( data + " / Ethos " );
};
Use it when you use
 
  
< script language = " javascript " type = " text/javascript " >

$(document).ready(
function () {

XLR8.feed.alert(
" Hello " );

XLR8.feed.load();

Ethos.common.copyright(
" Anytao " );
})

< / script>

Hey. It’s simple and useful.

谢谢浏览!

转载于:https://www.cnblogs.com/Music/archive/2011/07/08/how-to-use-namespace-in-javascript.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值