JavaScript 中的私有函数
在基于 jQuery 的 Web 应用程序中,我有各种脚本,其中可能包含多个文件,但我一次只使用其中一个(我知道不包含所有文件会更好,但我只负责 JS所以这不是我的决定)。因此,我将每个文件包装在一个 initModule()
函数中,该函数注册各种事件并进行一些初始化等。
现在我很好奇这些文件之间是否有任何差异以下两种定义函数的方法不会扰乱全局命名空间:
function initStuff(someArg) {
var someVar = 123;
var anotherVar = 456;
var somePrivateFunc = function() {
/* ... */
}
var anotherPrivateFunc = function() {
/* ... */
}
/* do some stuff here */
}
和
function initStuff(someArg) {
var someVar = 123;
var anotherVar = 456;
function somePrivateFunc() {
/* ... */
}
function anotherPrivateFunc() {
/* ... */
}
/* do some stuff here */
}
In a jQuery-based web application I have various script where multiple files might be included and I'm only using one of them at a time (I know not including all of them would be better, but I'm just responsible for the JS so that's not my decision). So I'm wrapping each file in an initModule()
function which registers various events and does some initialization etc.
Now I'm curious if there are any differences between the following two ways of defining functions not cluttering the global namespace:
function initStuff(someArg) {
var someVar = 123;
var anotherVar = 456;
var somePrivateFunc = function() {
/* ... */
}
var anotherPrivateFunc = function() {
/* ... */
}
/* do some stuff here */
}
and
function initStuff(someArg) {
var someVar = 123;
var anotherVar = 456;
function somePrivateFunc() {
/* ... */
}
function anotherPrivateFunc() {
/* ... */
}
/* do some stuff here */
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这两种方法之间的主要区别在于功能何时可用。在第一种情况下,函数在声明后可用,但在第二种情况下,它在整个范围内可用(称为提升)。
除此之外 - 它们基本上是相同的。
The major difference between these two approaches resides in the fact WHEN the function becomes available. In the first case the function becomes available after the declaration but in the second case it's available throughout the scope (it's called hoisting).
other than that - they're basically the same.
这是一个帮助我管理 javascript 中的模块的模型:
base.js:
module_one.js
this is a model that helped me to manage modules in javascript:
base.js:
module_one.js