繁体   English   中英

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

[英]How can I wrap code into a module in order to avoid using global variables?

上一个问题之后 ,我提出了以下工作代码,该代码旨在通过替换<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>

但是,正如接受的答案的作者所说,“还有其他方法[..]可以将所有这些代码包装到模块中”。 我不是JavaScript方面的专家,但是我想多了解一些。

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

您当前的代码如下所示:

var refreshTimer; //a global variable

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

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

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

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

main();

但是,用这种方法不能完全解决问题。 尽管确实摆脱了全局变量,但我们添加了一个新变量-“ 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(){}()) ,则会出现语法错误。

这是 JavaScript中模块模式的不错描述。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM