Recently colleagues in the write modify a JS in the Ajax callback function to take the outer variables as undefined, the sample code is as follows:
function A () {
var amount=18;
$.post ("/charges/selfpayment/keepconn", function (data) {
alert (amount); Eject undefined
if (true) {
var amount=19;
}
alert (amount);/eject
});
A ();
Even in the first line of the Ajax callback function, alert out of the outer variable is still undefined, I looked at the code and found that other than this variable is normal to the value, so I carefully check the problem of the variable itself, according to the scope of the global variables to exclude the effect of the reason, There is a place in the callback function that defines the new variable, the name is the same as the outer variable to be accessed, considering that JS is an interpreted language and does not care too much about the variables defined after my alert, it turns out that it is normal to block out the declaration of this variable with the same name.
My mother told me that this is called: variable declaration elevation (hoisting), the definition of a variable to be elevated to the interpretation before execution (the function is also a variable), where it is necessary to note that "ascension" is only defined, so the first alert in the example above pops up undefined instead of 19, Because the previous did not study these bottom things properly, by their own imagination that interpretation is simply rough line of execution.
In addition, because JS does not have a block-level scope, the variable defined in the IF statement can also access the