"JavaScript" variable promotion and var for variable promotion

Source: Internet
Author: User

JavaScript's declared variable promotion often affects our normal access to variables, so close this article so that we can flip through it later.

What is variable elevation
//Variable declaration promotionfunction Test(){    varA= "1";    varF= function(){};    varB= "2";    varC= "3";}//The above code is equivalent tofunction Test(){    varA,F,B,C;A= "1";F= function(){};B= "2";C= "3";}

There are two scenarios for defining variables in JS: (Note that you cannot define a variable without var outside of the method, and that the occurrence of XX is not defined)

  1. Plus Var, which is a local variable within the method, and a global variable outside the method.
  2. Within a method, add var to a local variable, and no var is a global variable (after executing the current method)
Variable Promotion Case Study 1

Since the variable A is defined inside the Test1 function,

var='I\'m a in all'functiontest1{    console.log(a)    console.log(window.a)    var='I\'m a in test1'    console.log(a)}    test1()

The above code is equivalent to

var='I\'m a in all'functiontest1{    var a    console.log// undefined    console.log(window.a// I'm a in all(因为window指的是全局环境)    ='I\'m a in test1'    console.log// I'm a in test1}    test1()
Case 2
var='I\'m a in all'functiontest2{    console.log// I'm a in all    ='I\'m a in test2'// 这里本来就是赋值,所以上边的a会输出全局变量    console.log// I'm a in test2}test2()
Case 3
functiontest3{    console.log// 报错(Uncaught ReferenceError: a is not defined)    ='I\'m a in test3'// 这里本来就是赋值,所以上边的a会输出全局变量    console.log// I'm a in test3}test3()console.log(2// I'm a in test3(本来没有全局变量a,当test3运行时,定义了一个全局变量a,所以这里会输出)

"JavaScript" variable promotion and var for variable promotion

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.