Bug sample code caused by js implicit global variables
- 2020-03-30 02:43:40
- OfStack
A js code encountered a bug caused by an implicit global variable in the middle,
Because of the amount of code, the problem was found through the javascript debugger of the Google browser.
I said I couldn't install fiefox on my computer in any case, and I tried many times since last year, all of which failed.
But the debugging of Google is also useful.
The simplified code is as follows:
In js, it is recommended that all variables be declared with var, and all variables can be written to the top, because js has no block-level scope.
Because of the amount of code, the problem was found through the javascript debugger of the Google browser.
I said I couldn't install fiefox on my computer in any case, and I tried many times since last year, all of which failed.
But the debugging of Google is also useful.
The simplified code is as follows:
$(function(){
var pageNo = 2;//This parameter is variable
var pageSize = 10;
test();
paginate(pageNo,pageSize);//Because the test() method overrides the pageNo, the pageNo is always equal to 1
});
function test(){
pageNo = 1;//Global variable, overwriting the previous pageNo, is equivalent to writing var pageNo = 1 at the top of js
//Var pageNo = 1; It is ok
//do,,,
}
function paginate(pageNo,pageSize){
window.location.href = "user_list.action?pageNo="+pageNo+"&pageSize="+pageSize;
}
In js, it is recommended that all variables be declared with var, and all variables can be written to the top, because js has no block-level scope.