如何在JavaScript中创建命名空间,使我的对象和函数不被其他同名对象和函数覆盖?我使用了以下方法:

if (Foo == null || typeof(Foo) != "object") { var Foo = new Object();}

有没有更优雅或更简洁的方式来做到这一点?


当前回答

在JavaScript中,没有预定义的方法来使用名称空间。在JavaScript中,我们必须创建自己的方法来定义NameSpaces。下面是我们在Oodles技术中遵循的一个过程。

注册命名空间 下面是注册名称空间的函数

//Register NameSpaces Function
function registerNS(args){
 var nameSpaceParts = args.split(".");
 var root = window;

 for(var i=0; i < nameSpaceParts.length; i++)
 {
  if(typeof root[nameSpaceParts[i]] == "undefined")
   root[nameSpaceParts[i]] = new Object();

  root = root[nameSpaceParts[i]];
 }
}

要注册一个命名空间,只需调用上述函数,参数为名称空间,以'分隔。”(点)。 例如 让您的应用程序名称为oodles。可以通过以下方法创建命名空间

registerNS("oodles.HomeUtilities");
registerNS("oodles.GlobalUtilities");
var $OHU = oodles.HomeUtilities;
var $OGU = oodles.GlobalUtilities;

基本上,它会在后端创建你的命名空间结构,如下所示:

var oodles = {
    "HomeUtilities": {},
    "GlobalUtilities": {}
};

在上面的函数中,您注册了一个名为“oodles”的命名空间。homeuutilities”和“oodles.GlobalUtilities”。为了调用这些命名空间,我们创建了一个变量,即var $OHU和var $OGU。

这些变量只是初始化名称空间的别名。 现在,当你声明一个属于HomeUtilities的函数时,你会像这样声明它:

$OHU.initialization = function(){
    //Your Code Here
};

上面是函数名初始化,并将其放入命名空间$OHU中。并在脚本文件中的任何地方调用此函数。只需使用下面的代码。

$OHU.initialization();

类似地,对于另一个NameSpaces。

希望能有所帮助。

其他回答

我使用在企业jQuery网站上找到的方法:

下面是他们的例子,展示了如何声明私有和公共属性和函数。一切都是作为一个自动执行的匿名函数完成的。

(function( skillet, $, undefined ) {
    //Private Property
    var isHot = true;

    //Public Property
    skillet.ingredient = "Bacon Strips";

    //Public Method
    skillet.fry = function() {
        var oliveOil;

        addItem( "\t\n Butter \n\t" );
        addItem( oliveOil );
        console.log( "Frying " + skillet.ingredient );
    };

    //Private Method
    function addItem( item ) {
        if ( item !== undefined ) {
            console.log( "Adding " + $.trim(item) );
        }
    }
}( window.skillet = window.skillet || {}, jQuery ));

如果你想访问某个公共成员你只需输入skillet。fry()或skillet。配料。

真正酷的是,现在可以使用完全相同的语法扩展名称空间。

//Adding new Functionality to the skillet
(function( skillet, $, undefined ) {
    //Private Property
    var amountOfGrease = "1 Cup";

    //Public Method
    skillet.toString = function() {
        console.log( skillet.quantity + " " +
                     skillet.ingredient + " & " +
                     amountOfGrease + " of Grease" );
        console.log( isHot ? "Hot" : "Cold" );
    };
}( window.skillet = window.skillet || {}, jQuery ));

第三个未定义的参数

The third, undefined argument is the source of the variable of value undefined. I'm not sure if it's still relevant today, but while working with older browsers / JavaScript standards (ecmascript 5, javascript < 1.8.5 ~ firefox 4), the global-scope variable undefined is writable, so anyone could rewrite its value. The third argument (when not passed a value) creates a variable named undefined which is scoped to the namespace/function. Because no value was passed when you created the name space, it defaults to the value undefined.

我最近最喜欢的图案是这样的:

Var命名空间=(函数(){ //暴露给公众 返回{ internalA, c: internalC } //所有私有 /** *完整的JSDoc * / 函数internalA() { / /…… } /** *完整的JSDoc * / 函数internalB() { / /…… } /** *完整的JSDoc * / 函数internalC() { / /…… } /** *完整的JSDoc * / 函数internalD() { / /…… } }) ();

当然,return可以在后面,但是如果后面只有函数声明,那么就更容易看到名称空间是关于什么的,以及暴露了什么API。

在这种情况下使用函数表达式的模式导致不遍历整个代码就无法知道公开了哪些方法。

我使用这种方法:

var myNamespace = {}
myNamespace._construct = function()
{
    var staticVariable = "This is available to all functions created here"

    function MyClass()
    {
       // Depending on the class, we may build all the classes here
       this.publicMethod = function()
       {
          //Do stuff
       }
    }

    // Alternatively, we may use a prototype.
    MyClass.prototype.altPublicMethod = function()
    {
        //Do stuff
    }

    function privateStuff()
    {
    }

    function publicStuff()
    {
       // Code that may call other public and private functions
    }

    // List of things to place publically
    this.publicStuff = publicStuff
    this.MyClass = MyClass
}
myNamespace._construct()

// The following may or may not be in another file
myNamespace.subName = {}
myNamespace.subName._construct = function()
{
   // Build namespace
}
myNamespace.subName._construct()

外部代码可以是:

var myClass = new myNamespace.MyClass();
var myOtherClass = new myNamepace.subName.SomeOtherClass();
myNamespace.subName.publicOtherStuff(someParameter);

我们可以这样单独使用它:

var A = A|| {};
A.B = {};

A.B = {
    itemOne: null,
    itemTwo: null,
};

A.B.itemOne = function () {
    //..
}

A.B.itemTwo = function () {
    //..
}

我喜欢这个:

var yourNamespace = {

    foo: function() {
    },

    bar: function() {
    }
};

...

yourNamespace.foo();