如何将代码包装到模块中以避免使用全局变量?

时间:2013-09-19 23:44:35

标签: javascript jquery design-patterns module global-variables

在我previous question之后,我提出了以下工作代码,该代码旨在通过替换<div id="test_css_id">...</div>本身来定期刷新DOM。以下代码中出现的两个AJAX请求的行为是重新加载相同的代码本身。

<div id="test_css_id">
  <a id="link_css_id" href="test_url.html">LINK</a>

  <script type="text/javascript">
    var refreshTimer; 

    $('#link_css_id').click(function(event) {
      event.preventDefault();

      $.ajax({
        url:     $(this).attr('href'),
        type:    'PUT',
        success: function(data) {
          clearInterval(refreshTimer);
          $('#test_css_id').replaceWith(data); // Replaces all code including JavaScript with the response data (note: the response data is exactly the same as the code shown here).
        }
      });
    });

    $(document).ready(function() {
      function refreshFunction(){
        $.ajax({
          url:     'test_url.html',
          type:    'GET',
          success: function(data) {
            clearInterval(refreshTimer);
            $('#test_css_id').replaceWith(data); // Replaces all code including JavaScript with the response data (note: the response data is exactly the same as the code shown here).
          }
        });
      }

      refreshTimer = setInterval(refreshFunction, 1000);
    });
  </script>
</div>

然而,正如accepted answer的作者所说,“还有其他方法可以做到[..]一种方法是将所有代码包装到一个模块中”。我不是JavaScript的专家,但我想了解并学习更多。

如何将所有代码包装到模块中以避免使用全局变量?

2 个答案:

答案 0 :(得分:1)

您当前的代码如下所示:

var refreshTimer; //a global variable

$(...).click(...);

要使refreshTimer不是全局的,您需要将其放在函数中:

function main(){
   var refresherTimer; //this variable is now local to "main"

   $(...).click(...);
}

main();

然而,这样做并不能完全解决问题。虽然我们确实摆脱了全局变量,但我们添加了一个新的 - “主要”函数本身。

最后一招是将“main”函数转换为匿名函数并直接调用它。这是着名的“模块模式”:

(function(){
   var refreshTimer; //local variable to that anonymous function

   $(...).click(...);
}()); //and here we call the function to run the code inside it.

围绕一切的额外括号非常重要。如果您只是function(){}()而不是(function(){}()),那么您将收到语法错误。

答案 1 :(得分:0)

Here's JavaScript中模块模式的一个很好的描述。

相关问题