Javascript 使变量不是全局变量
我想知道当变量需要在同一个模块中的多个函数之间使用时,防止它们成为全局变量的最佳方法是什么 正如你所看到的,我需要这些变量在整个过程中都是可用的,但我不一定要在全局中定义,因为那样最终会把事情搞砸。我是否将它们包装在函数中 另外,如果有人对如何改进这段代码有任何建议,我很乐意听听 下面是我的代码示例:Javascript 使变量不是全局变量,javascript,jquery,variables,Javascript,Jquery,Variables,我想知道当变量需要在同一个模块中的多个函数之间使用时,防止它们成为全局变量的最佳方法是什么 正如你所看到的,我需要这些变量在整个过程中都是可用的,但我不一定要在全局中定义,因为那样最终会把事情搞砸。我是否将它们包装在函数中 另外,如果有人对如何改进这段代码有任何建议,我很乐意听听 下面是我的代码示例: // Info Bullet Slide Out var slideOut, clickedButton, clickedParent, activeClass = 'i
// 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();
}
});
将所有内容包装到函数中:
(function(){
// all your code
})();
变量的作用域将是匿名的自调用函数包装器。将所有内容包装到函数中:
(function(){
// all your code
})();
变量的作用域将是匿名的、自调用的函数包装器。全局作用域很糟糕-使用IIFE来包装一切!谢谢你,克里斯,现在读这篇文章。如果所有内容都在
$(document).ready(function()…)
中,那么它不在全局范围内,它在该函数的范围内。全局范围很糟糕-使用IILife来包装所有内容!谢谢Chris,现在阅读本文。如果所有内容都在$(document).ready(function()…)
中,那么它不在全局范围内,而是在该函数的范围内。