1

我做错了什么还是这不可能:

(function(namespace,undefined)
{
    //Private properties and methods
    var foo="bar";
    function test(){return foo;}

    //Public properties and methods
    namespace.foobar=foo+"123";
    namespace.showFoo=function(){return test();};
})(window.namespace=window.namespace || {});

然后我尝试“扩展”上述命名空间并添加一个新方法:

(function(namespace,undefined)
{
    //Public method
    namespace.sayGoodbye=function()
    {
        alert(namespace.foo);
        alert(namespace.bar);
        alert(test());
    }
})(window.namespace=window.namespace || {});

警报显示undefined属性并引发方法错误test()

谢谢。

4

3 回答 3

3

你为什么期望拥有foobar可用?这些标识符永远不会在namespace任何地方分配给您的对象。

任何声明的变量var仅在当前激活/变量对象的函数(-上下文)中可用。function declarations在你的情况下,同样适用test()。这两个都只存储在第一个匿名函数的 AO 中,而不是存储在您的namespace对象中。您必须明确分配值

namespace.foo = foo;
namespace.bar = "hello I am bar";
于 2011-10-12T10:06:14.937 回答
1

命名空间声明和命名空间扩展:

var namespace = function(str, root) {
    var chunks = str.split('.');
    if(!root)
        root = window;
    var current = root;
    for(var i = 0; i < chunks.length; i++) {
        if (!current.hasOwnProperty(chunks[i]))
            current[chunks[i]] = {};
        current = current[chunks[i]];
    }
    return current;
};

// ----- USAGE ------

namespace('ivar.util.array');

ivar.util.array.foo = 'bar';
alert(ivar.util.array.foo);

namespace('string', ivar.util); //or namespace('ivar.util.string');

ivar.util.string.foo = 'baz';
alert(ivar.util.string.foo); 

试试看:http: //jsfiddle.net/stamat/Kb5xY/

博文:http ://stamat.wordpress.com/2013/04/12/javascript-elegant-namespace-declaration/

于 2013-04-12T13:09:32.113 回答
1

您的代码中有几个错误。该代码正在运行。例子

(function(namespace)
{
    if(namespace === undefined) {
        window.namespace = namespace = {};
    }

    //Private properties and methods
    var foo="bar";
    function test(){return foo;}

    //Public properties and methods
    namespace.foobar=foo+"123";
    namespace.showFoo=function(){return test();};
})(window.namespace);

(function(namespace)
{
    if(namespace === undefined) {
        window.namespace = namespace = {};
    }

    //Public method
    namespace.sayGoodbye=function()
    {
        alert(namespace.foobar);
        alert(namespace.showFoo());
    }
})(window.namespace);

window.namespace.sayGoodbye();

错误: 1. 您从未设置变量 window.namespace。2. 如果您在函数中以私有方式声明变量/函数,则只有该特定函数才能访问这些变量/函数。如果你想使用命名空间,你可以这样做:

var namespace = (function(){
        var private = "private";
        function privateFunc() {
                return private;
        }
        return {
            "publicFunc": function(){return privateFunc()}
        }
    })();
namespace.publicFunc() === "private";
//alert(namespace.publicFunc());


// extend namespace
(function(namespace){
    var private = "other private";
    namespace.newFunc = function(){return private};
})(namespace);
namespace.newFunc() === "other private";
//alert(namespace.newFunc());
于 2011-10-12T10:26:33.217 回答