JS local variables and global variables

Source: Internet
Author: User

In the outermost definition is the global variable

If you do not use VAR to declare directly assigned variables inside a function, then this variable is also a global variable

Variables declared with Var inside a function are called local variables

Defined at the beginning of the global variable in the entire JS range can be accessed, can be used, defined in the indefinite position of the global variable, only after the definition of variables to use the variable, if a variable is defined in a function, and declared with Var, it is a local variable, only valid in the method body, parameters are local variables , in the method body, can not be accessed, if the variable is assigned directly in the body of the method, without Var declaration, it is a global variable, but only after the function is executed to be externally accessible, if not executed, this variable can still access the

The return value of a function can be used as a parameter to another function, so that the callback function

123456789101112131415161718 <script>window.onload=function(){    var y=1;//属于全局变量    function show(x){        var num=2;        sum=3;        return num*x;    }    //show();    //alert(num);出现错误,num的作用域仅限于方法体内    //alert(x);出现错误,参数a的作用与仅限于方法体内    alert(sum);//弹出sum的值,方法体内不用var声明的变量,不仅仅作用于方法体内,相当于全局变量(注意,只有在方法运行后才能访问到,否则会提示sum is not defined)    function fun(){        return 5;    }    alert(show(fun()));//这属于回调函数,回调函数是将一个函数的返回值直接作为另一个函数的参数进行计算的方式}</script>

JS local variables and global variables

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.