JavaScript -- name spacejavascript

来源:互联网 发布:重装系统哪个软件好 编辑:程序博客网 时间:2024/05/23 15:30

creating namespaces in javascript

in the past it was very common to see global variables in snippets of javascript code across the web, such as:

name = "spock";

function greeting() {

return "hello " + name;

}

a better approach is to place all of your code within a namespace; an object that contains all of your code and helps to prevent name clashes with javascript code written by others.

the simplest method of creating a namespace is to use an object literal.

var foo = {};

foo.name = "spock";

foo.greeting = function() {

return "hello " + foo.name;

}

this can also be specified using a different syntax.

var foo = {

name: "spock",

greeting: function() {

return "hello " + foo.name;

}

};

this approach is better that having outright global variables, but it exposes everything within the namespace as global. in other words both foo.name and foo.greeting are available everywhere.

another problem with this approach is that greeting needs to refer to ‘foo.name’ rather than just ‘name’.

another method of creating a namespace is through the use of a self executing function.

var foo = (function(){

// create a private variable

var name = "spock";

// create a private function

var greeting = function() {

return "hello " + name;

};

// return an object that exposes our greeting function publicly

return {

greeting: greeting

};

})();

here, when the function is executed it creates a private variable and a private inner function. the inner function can refer to the private variable directly. the main function then returns an object literal containing a reference to the greeting private function – this then exposes the greeting function as a public function so we can call it via the foo namespace.

console.log(foo.greeting() === "hello spock"); // true

javascript 的命名空间并不是真正的命名空间, 只是在脚本内部创建一个封闭的小空间, 必须通过特定的空间名称才能对空间内部的代码进行访问, 这样可以防止同名函数和变量发生冲突, 也可以更方便地管理代码, 就像 .net 的命名空间 (namespace) 和 java 的包 (package) 一样.

为什么需要命名空间?

1. javascript 是不会禁止你重复定义函数和变量的, 但他只会使用最后定义的版本, 也就是说, 这将导致前面的失效, 令系统出错. 比如, $(id) 是最常用的, 也许你会毫不犹豫的在自己的脚本上定义这个函数, 但是当你用上 prototype, 你就会发现, 它和 prototype 的函数冲突, 并导致你的页面跑不动了. 怎么办? 这时候就需要命名空间了. 我发布的主题里面的 javascript 都有用命名空间包起来的, 我这么做就是为了防止和某些插件的代码发生冲突.

2. 如果你要为自己准备一套常用的函数, 或者自己搭建一个 framework, 那这个方法可以使你的代码维护起来更加方便.

怎么使用命名空间?

看以下代码, 命名空间里面定义了两个函数, 将空间命名为 mynamespace, 并声明了 $ 的对外接口. 也就是说, 我们可以在空间外部通过 mynamespace.$ 来调用 $ 函数, 但 mymethod 函数只能在空间内部使用. 因为外部调用需要通过空间来调用, 所以不会和外部函数发生冲突. 变量同理.

(function() {

// 通过 id 获取 element 对象

function $(id) {

return document.getelementbyid(id);

}

// 显示对应 id 的对象的节点类型名字

function mymethod(id) {

alert($(id).nodename);

}

// 这是对外的接口

window['mynamespace']= {}

window['mynamespace']['$'] = $;

})();

原创粉丝点击