如何避免JavaScript中的全局变量

时间:2017-02-24 00:05:25

标签: javascript variables global

如何避免在JavaScript中使用全局变量?

  //load more
  var size_li = $("#myList li").size();
  var x = 3;
  $('#myList li:lt(' + x + ')').show();
  $('.loadmore').on('click', function() {
      x = (x + 2 <= size_li) ? x + 2 : size_li;
      $('#myList li:lt(' + x + ')').show();
  });

2 个答案:

答案 0 :(得分:1)

一个好的技巧是自动执行闭包:

// bob is a global variable, which you want to avoid
var bob = 1;

// By wrapping this function declaration in parentheses, then
// appending (), it gets invoked immediately. But everything
// inside it is scoped to the anonymous function!
(function () {
    // sue can only be seen inside this function
    var sue = 1;

    // But if you want to, you can still create global variables.
    // This creates a global variable called joe:
    window.joe = 1;
})();

将此技术应用于您的代码,您可以将其写为没有全局变量:

(function() {
    var size_li = $("#myList li").size();
    var x = 3;

    $('#myList li:lt(' + x + ')').show();
    $('.loadmore').on('click', function() {
        x = (x + 2 <= size_li) ? x + 2 : size_li;
        $('#myList li:lt(' + x + ')').show();
    });
})();

答案 1 :(得分:-1)

我所知道的方式是es6,它让我们感受到了#6;可以在块

中定义变量

例如:

var b = 5
{
let a = 10
}
a//undefine
b// is 5