javascript 命名空间,学习

时间:2024-05-20 11:33:20

一、

(function(){
var _NS=function(){ }
_NS.prototype.alert=function(){
console.log('test');
}
window.NS=new _NS();
})();

二、

// 声明一个全局对象Namespace,用来注册命名空间
Namespace = new Object(); // 全局对象仅仅存在register函数,参数为名称空间全路径,如"Grandsoft.GEA"
Namespace.register = function(fullNS)
{
// 将命名空间切成N部分, 比如Grandsoft、GEA等
var nsArray = fullNS.split('.');
var sEval = "";
var sNS = "";
for (var i = 0; i < nsArray.length; i++)
{
if (i != 0) sNS += ".";
sNS += nsArray[i];
// 依次创建构造命名空间对象(假如不存在的话)的语句
// 比如先创建Grandsoft,然后创建Grandsoft.GEA,依次下去
sEval += "if (typeof(" + sNS + ") == 'undefined') " + sNS + " = new Object();"
}
if (sEval != "") eval(sEval);
}
// 注册命名空间Grandsoft.GEA, Grandsoft.GCM
Namespace.register("Grandsoft.GEA");
Namespace.register("Grandsoft.GCM"); // 在Grandsoft.GEA命名空间里面声明类Person
Grandsoft.GEA.Person = function(name, age)
{
this.name = name;
this.age = age;
} // 给类Person添加一个公共方法show()
Grandsoft.GEA.Person.prototype.show = function()
{
alert(this.name + " is " + this.age + " years old!");
} // 演示如何使用类Person
var p = new Grandsoft.GEA.Person("yanglf", 25);
p.show();

三、

var YAHOO = window.YAHOO || {};

YAHOO.namespace = function(ns) {

    if (!ns || !ns.length) {
return null;
} var levels = ns.split(".");
var nsobj = YAHOO; // YAHOO is implied, so it is ignored if it is included
for (var i=(levels[0] == "YAHOO") ? 1 : 0; i<levels.length; ++i) {
nsobj[levels[i]] = nsobj[levels[i]] || {};
nsobj = nsobj[levels[i]];
} return nsobj;
}; YAHOO.extend = function(subclass, superclass) {
var f = function() {};
f.prototype = superclass.prototype;
subclass.prototype = new f();
subclass.prototype.constructor = subclass;
subclass.superclass = superclass.prototype;
if (superclass.prototype.constructor == Object.prototype.constructor) {
superclass.prototype.constructor = superclass;
}
}; YAHOO.namespace("util");
YAHOO.namespace("widget");
YAHOO.namespace("example");

四、

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();
*/