如何避免 JavaScript 中的全局变量
How to avoid global variables in JavaScript
如何避免在 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();
});
我知道的方法是在 es6 中,'let' 可以在块中定义一个变量
例如:
var b = 5
{
let a = 10
}
a//undefine
b// is 5
一个很好的技术是自执行闭包:
// 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();
});
})();
如何避免在 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();
});
我知道的方法是在 es6 中,'let' 可以在块中定义一个变量
例如:
var b = 5
{
let a = 10
}
a//undefine
b// is 5
一个很好的技术是自执行闭包:
// 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();
});
})();