使变量不是全局的

时间:2014-07-11 17:59:00

标签: javascript jquery variables

我想知道当变量需要在同一模块中的多个函数中使用时,防止变量为全局的最佳方法是什么。

正如你所看到的那样,我需要在整个过程中提供这些变量 - 但我并不一定希望在全球范围内定义这些变量,因为最终会将这些变量搞砸。我将它们包装在一个函数中吗?

此外,如果有人提出改进此代码的方法,我很乐意听到它。

这是我的代码示例:

// 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();
  }
});

1 个答案:

答案 0 :(得分:5)

将所有内容包装成函数:

(function(){

  // all your code

})();

变量的范围将是匿名的自调用函数包装器。

相关问题