扩展 JavaScript 命名空间
我是否做错了什么或者这根本不可能:
(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()
方法。
谢谢。
Am I doing something wrong or is this just not possible:
(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 || {});
Then I try to "extend" the above namespace and add a new method:
(function(namespace,undefined)
{
//Public method
namespace.sayGoodbye=function()
{
alert(namespace.foo);
alert(namespace.bar);
alert(test());
}
})(window.namespace=window.namespace || {});
The alert shows undefined
for the properties and throws an error for the test()
method.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(3)
为什么您希望有
foo
和bar
可用?这些标识符永远不会在任何地方分配给您的命名空间
对象。使用
var
声明的任何变量仅在当前激活/变量对象的 Function(-Context) 中可用。对于函数声明
也是如此,在您的例子中,test()
。这两个都仅存储在第一个匿名函数的 AO 中,而不存储在您的命名空间
对象中。您必须显式分配值Why would you expect to have
foo
andbar
available ? Those identifiers are never assigned to yournamespace
object anywhere.Any variable that is declared with
var
is only available in the Function(-Context) of the current Activation/Variable Object. Same goes forfunction declarations
, in your case,test()
. Both these are only stored within the AO from the first anonymous function and are not stored within yournamespace
object. You would have to explicitly assign the values您的代码中有几个错误。该代码正在运行。 示例。
错误:
1.您从未设置变量window.namespace。
2. 如果您在函数中以私有方式声明变量/函数,则只有该特定函数可以访问这些变量/函数。
如果你想使用命名空间,你可以这样做:
You have several bugs in your code. That code is working. Example.
Bugs:
1. You never set the variable window.namespace.
2. If you declare variables/functions in a private way in a function then only this specific function can access these variables/functions.
If you want to use a namespace you can do it like this:
命名空间声明和命名空间扩展:
尝试一下:http://jsfiddle.net/stamat/Kb5xY/
博客文章:http://stamat.wordpress.com/2013/04/12/javascript-elegant-namespace-declaration/
Namespaces declaration and extending of namespaces:
Try it out: http://jsfiddle.net/stamat/Kb5xY/
Blog post: http://stamat.wordpress.com/2013/04/12/javascript-elegant-namespace-declaration/