当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JavaScript 编程引入命名空间的方法

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 JavaScript 编程引入命名空间的方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 104 ::
收藏到网摘: n/a

JavaScript 代码一般最常见的语法格式就是定义函数 function xxx(){/*code...*/},经常有这样的一大堆函数定义。函数名很容易发生冲突,特别是引入多个js文件时,冲突的情况尤为明显。因此也就有引入命名空间的必要。
Javascript 本身没有命名空间的概念,需要用对象模拟出来。
比如定义一个命名空间的类,用于创建命名空间:
function NameSpace(){
}
这是一个构造函数,但却不做任何事情,再来下面和评论有关的代码:
var comment = new NameSpace();
comment.list = function(){/*code...*/};
comment.counter = 0;
第一行创建所谓命名空间(其实就是一个空白对象),名为comment,第二、三行定义该空间下的两个方法。调用时可以使用 comment.list() 或者 comment.counter++ 等;
再创建子命名空间:
comment.add = new NameSpace();
comment.add.post = function(){/*code...*/}
comment.add.check = function(){}
之所以引入命名空间的概念,是为了避免函数名相同的问题。上面的过程也可以这样定义:
var comment = {
list : function(){/*code...*/},
add : {
post : function(){/*code...*/},
check : function(){/*code...*/}
}
}
prototype.js 里面就大量使用这种方式,虽然这种方式更直观地像一棵树,但只要节点稍多一些,眼睛就忙于寻找这些节点的关系,命名空间的做法是横向地描述这种关系树,层次关系直接表现在字面上,两种方式效果一致,但书写风格却各有特点。