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

守給你的承諾、 提交于 2019-12-23 04:48:06

问题


After my previous question, I come up to the following working code that is intended to refresh the DOM periodically by replacing the <div id="test_css_id">...</div> itself. The behavior of both AJAX requests present in the below code is to reload the same code itself.

<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>

However, as said by the author of the accepted answer, "there are other ways you can do it [..] one way is to wrap all of that code into a module". I am not expert in JavaScript but I would like to understand and learn it a little more.

How can I wrap all of that code into a module in order to avoid using global variables?


回答1:


Your current code looks like this:

var refreshTimer; //a global variable

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

To make refreshTimer not global, you need to put it inside a function:

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

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

main();

However, doing it this way won't solve the problem completely. While we did get rid of the global variables, we added a new one - the "main" function itself.

The final trick is to turn the "main" function into an anonymous function and invoke it directly. This is the famous "module pattern":

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

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

The extra parenthesis around everything are important. If you do just function(){}() instead of (function(){}()) then you will get a syntax error.




回答2:


Here's a nice description of the module pattern in JavaScript.



来源:https://stackoverflow.com/questions/18906723/how-can-i-wrap-code-into-a-module-in-order-to-avoid-using-global-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!