Javascript 转换为命名空间并调用函数
我是一个典型的 Web 开发人员,在 JS 中使用全局的一切。我现在已经看到曙光并希望转换为命名空间。因此,在我当前的项目中,我有一个页面,该页面具有三个 JS 函数(当前均为全局函数),在调用时将文本分配给锚点并附加单击方法来切换特定 div 的可见性。非常标准。
因此,示例函数写为:
function toggleComments(){
$("comments-section").hide();
$("comments-button").click(function (){
blah
return false;
});
}
我的问题是如何创建一个命名空间来保存这些函数然后调用它们?
我发现了不同的例子,但没有结论性的。
任何帮助都会很棒。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
billy Moon 显示了一个良好的开端,但使用对象文字的问题是您无法交叉引用其他字段/函数/属性。
我更喜欢揭示模块模式(参见 http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/ )
揭示模块模式结合了自执行函数、闭包的利用(某种程度)来提供内部私有函数/字段,并允许您传递参数来初始化命名空间对象。
您可以看到命名空间对象包含一个私有字段
somePrivateField
,可以从公共访问方法中引用该字段。另外,请注意,我已经公开了一个公共字段,并接受了一些我可以在函数等中使用/引用的参数(如果没有传入任何内容,您可以将其默认为某些默认值。可以像这样使用:
我喜欢这个的原因之一是只需浏览自执行函数返回的对象文字,就可以很容易地看出什么是公共/私有
希望这有帮助
billy moon shows a good start, but the problem with using object literals, is that you cannot cross reference other fields/functions/properties.
I much prefer the revealing module pattern (see http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/)
the revealing module pattern combines a self-executing function, an exploitation (of sorts) of closures to provide internal private functions/fields, and allows you to pass params to initialise your namespaced object.
You can see that the namespaced object contains a private field
somePrivateField
, which can be referenced from publicly accessible methods. Also, notice i have exposed a public field, and accepted some params which i may use/reference in functions etc (and you can default it to some default if nothing is passed in.can be used like this:
one reason i like this is that it's very easy to see what is public/private by just glancing at the object literal returned from the self-executing function
Hope that's helpful
此外,您应该尝试将代码包含在匿名自调用函数中。这意味着您可以在全局命名空间中没有任何内容,因此没有污染的风险。
Additionally, you should try to contain your code in an anonymous self invoking function. This means you can have nothing in the global namespace, therefore no risk of pollution.