这两种命名空间方法有什么区别?
我的代码目录中的第一个文件如下
myNamespace.js
var myNamespace = {};
然后我的后续文件可以看起来像以下两种方式之一。
第一个
(function (ns) {
ns.DoStuff = function(){
// do stuff
}
})(myNamespace);
第二个
myNamespace.DoStuff = function(){
//do stuff
}
那么这两种方法有什么区别呢?两者似乎都适合我。有没有更普遍接受的约定?
抱歉,对 javascript 还很陌生
I've got the first file in my code directory as follows
myNamespace.js
var myNamespace = {};
Then my subsequent files can look as one of the two following ways.
first
(function (ns) {
ns.DoStuff = function(){
// do stuff
}
})(myNamespace);
second
myNamespace.DoStuff = function(){
//do stuff
}
So what is the difference between these two methods? Both seem to work for me. Is there a more generally accepted convention?
sorry, still new to javascript
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的第一种方法不会起作用。它将在
全局对象
(很可能窗口
)上创建DoStuff
。您需要将this
替换为ns
,执行此操作后,两种方法之间没有区别。前者的优点是您可以将所有应用程序/文件相关的内容关闭到外部自调用关闭函数中。所以你不会破坏全局命名空间。
Your first approach will not work. It would create
DoStuff
on theglobal object
(most likelywindow
). You would need to replacethis
withns
, after you did that, there is no difference between the two approaches.The former will have the adventage that you might be able to closure all your application/file related stuff into that outer self-invoking closure function. So you won't clobber the global namespace.
您的第一个方法有错误,您使用了
this
,我很确定您的意思是ns
:撇开这一点,您的第一种方法往往会更好,因为您已经为自己创建了一个很好的小作用域函数,它允许您为您在名称空间上创建的所有公共方法提供私有数据和函数,而无需将它们设为全局变量。例如:
我喜欢这样做,部分原因是我反对匿名函数,所以我不会像上面那样定义
DoStuff
,而是像这样:现在我分配给
myNamespace.DoStuff
的函数有一个正确的名称,当我调试代码时帮助我。但该名称不会污染全局名称空间,这有助于我保持理智并避免与其他代码发生冲突。You have an error in your first one, you've used
this
where I'm pretty sure you meantns
:Leaving that aside, your first approach tends to be better because you've created a nice little scoping function for yourself, which allows you to have private data and functions available to all of the public methods you create on your namespace, without making them globals. E.g.:
I like doing it that way partially because I have thing against anonymous functions, and so I wouldn't define
DoStuff
as above, but rather like this:Now the function I've assigned to
myNamespace.DoStuff
has a proper name, which helps me out when I'm debugging my code. But that name doesn't pollute the global namespace, which helps me stay sane and avoid conflicts with other code.