【发布时间】:2014-07-11 17:59:00
【问题描述】:
我想知道当变量需要在同一模块内的多个函数中使用时,防止变量成为全局变量的最佳方法是什么。
如您所见,我需要这些变量始终可用 - 但我不一定希望在全局中定义它们,因为这最终会搞砸事情。我是否将它们包装在一个函数中?
另外,如果有人对如何改进此代码有任何建议,我很乐意听到。
这是我的代码示例:
// Info Bullet Slide Out
var slideOut,
clickedButton,
clickedParent,
activeClass = 'is-active',
openClass = 'is-open';
function closeSlideOut(){
$('.tlx-img-point').removeClass(activeClass);
slideOut.removeClass(openClass);
clickedParent.removeClass(activeClass);
}
function openSlideOut(){
slideOut = $('.' + clickedButton.attr('id'));
slideOut.addClass(openClass);
clickedParent.addClass(activeClass);
clickedButton.addClass(activeClass);
}
$('.tlx-img-point').on('click', function(){
clickedButton = $(this);
clickedParent = clickedButton.parent();
// If you clicked on the same button twice just close the slideout
if($(this).hasClass('is-active')){
closeSlideOut();
// If you clicked on another info button close this one and open the new one
}else if(clickedParent.hasClass(activeClass)){
closeSlideOut();
// Delay 5ms to allow css animation to complete
setTimeout(function(){
openSlideOut();
}, 650);
// Open the info slide out
}else{
openSlideOut();
}
});
【问题讨论】:
-
全局范围很糟糕 - 使用 IIFE 来包装所有内容! benalman.com/news/2010/11/…
-
谢谢克里斯,现在阅读这篇文章。
-
如果所有内容都在
$(document).ready(function()...)内,那么它不在全局范围内,而是在该函数的范围内。
标签: javascript jquery variables