JavaScript 命名空间模式(类似于对象的属性)
这种模式的目的是什么?
var ns=function(){
//do some stuff
}
ns.test=function(){
//do another stuff
}
我看到了与此类似的代码,但我不明白这种模式的优点。
看起来这也类似于对象的属性。
这种模式有时也与闭包一起使用,似乎 jquery 使用它,但不确定。
谢谢!
what purpose of such pattern?
var ns=function(){
//do some stuff
}
ns.test=function(){
//do another stuff
}
I saw code that is similar to that, but I don't understand advantages of such pattern.
Also seems like this is similiar to properties of objects.
also this pattern some times used with closures, and it seems that jquery uses it, but not sure about that.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一方面,它确保您的变量和函数名称不会与可能包含的其他脚本的名称(例如广告、分析、没有命名空间的库等)发生冲突。
For one thing, it ensures that your variable and function names do not clash with names from other scripts that may be included (like advertising, analytics, libraries that don't namespace etc).
这种模式的出现是因为在 JavaScript 中,函数是具有自己的属性和方法的一流对象。这允许函数自己执行,但也可以模仿其他语言的东西。这允许你做一些非常强大的事情,比如模仿静态类、记忆、命名空间等。
This pattern arises because in JavaScript, functions are first-class objects with their own properties and methods. This allows functions to be executed by themselves, but also mimic things in other languages. This allows you to do some pretty powerful things like mimicing static classes, memoization, namespacing, etc.