JavaScript explain execution is not what I thought of as a simple rough __javascript

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.