Home  >  Article  >  Web Front-end  >  Detailed explanation of JavaScript variables and scope

Detailed explanation of JavaScript variables and scope

jacklove
jackloveOriginal
2018-06-11 17:47:491695browse

If you have never been to Tiananmen, the Forbidden City, and the Great Wall, it means you have never been to Beijing. If you don't understand the scope of JS variables, it's equivalent to not learning JS. Learn about the importance of JS variable scope for yourself! Tip: Remember to read the comments when reading this article!

JS is a weakly typed (loosely typed) language, which means that it is inherently different and unique!
Before explaining variable scope, let’s first understand the variables in JS. Variables in JS are very different from other languages. Because JS variables have a loose (not mandatory) nature, they are just a name that holds a specific type of value at a specific stage.

JS variables contain two different data types: basic data types (value types) and reference data types (complex data types).

Values ​​of basic data types are stored in stack memory. The value of the reference data type is stored in the heap memory, and only the pointer address of the reference type is retained in the stack memory.
There are five basic types of values: undefined, Null, Boolean, Number and String. Values ​​of basic data types are stored in stack memory.

//在栈内存中开辟一块空间存储值为"laotie"的变量namevar name="laotie";//在栈内存中开辟一块空间存储值为"laotie"的变量name2var name2=name;//name与name2是相对独立的,所以改变name2的值为"xiaozhang",而name的值不会受到影响var name2="xiaozhang";
console.log(name);//laotieconsole.log(name2);//xiaozhang

Let’s take a look at reference types again:

/*在栈内存中存放 obj的地址
* 其值存放在堆内存中。
* 栈内存的地址的指向堆内存中的值。*/var obj={
    name:"zhangpeiyue"}/*将obj的地址赋值给obj2
所以在栈内存中存储的地址与obj的地址相同,
obj与obj2共享同一个值。
*/var obj2=obj;
obj2.name="xiaozhang";//因为obj与obj2共享同一个值,所以上行代码改变的是同一个值console.log(obj.name);//xiaozhang
 //你也可以认为obj即为obj2,引用类型比较的是地址,因此为trueconsole.log(obj==obj2);//true
Next, let’s look at the comparison between basic data types and reference types.
  • Basic data types Comparison, the comparison is the value:

#
//基本数据类型比较的是值,只要值相等比较结果即为truevar a=1;var b=1;console.log(a==b);//truevar c=2;var d=c;console.log(c==d);//true
  • Reference type comparison, the comparison is the address:

var obj={
    age:12}var obj2={
    age:12}//引用类型比较的是地址,而不是值。//由于每次创建的引用类型地址都不同,所以结果为falseconsole.log(obj==obj2);//falsevar obj3={
    age:12}//将obj3的地址赋值给obj4。所以地址相同var obj4=obj3;//由于比较的是地址,且obj3与obj4的地址相同,所以结果为trueconsole.log(obj3==obj4);
Come again Take a look at the issue of basic types and reference types as parameters in functions
  • Basic types are used as parameters, and parameters are local variables

/*接收的所有基本数据类型,接收的是其值。
接收的参数都是函数体中的局部变量。
在函数体内改变值,对外部不会产生任何影响*/function fn(a){
    a+=1;
    console.log(a);//14}
var a=13;fn(a);
console.log(a);//13
  • Reference data type as parameter, parameter is global variable

/*引用数据类型传递的是引用地址,
因此函数体中的obj与函数外的obj的引用地址相同。
所以函数体中的obj与函数外的obj共享同一值,
改变其中一个值,其它的也会随之改变
*/function fn(obj){
    obj.name="laowang"
    console.log(obj.name);//laowang}
var obj={
    name:"laotie"}fn(obj);
console.log(obj.name);//laowang
Finally let’s talk about scope! JS variable scope refers to the scope of influence of the variable. Scope in JS is divided into global scope and local scope (function scope). Variables defined in the global scope are global variables, and variables defined in the local scope are local variables.

The global scope is the most peripherally defined scope. In web browsers, the global scope refers to the window object. Therefore, you can think of variables and functions defined in the global scope as properties and methods of the window object!

var color="red";//定义一个全局colorfunction fn(){
    color="blue";//全局函数可以在函数内访问}fn();
console.log(color);//blue
  • Global variables and functions are properties and methods of the window object.

var color="red";//定义一个全局colorfunction fn(){    color="blue";//全局函数可以在函数内访问}window.fn();
console.log(window.color);//blue
  • The variables declared in the function scope have the same name as the variables declared in the global scope

var color="yellow";//定义全局变量colorfunction fn(){    //在函数体内如果拥有指定的变量,就不会去外层查找
    var color="red";//这里是局部变量color,外面是访问不到的哦
    console.log(color);//red}fn();
console.log(color);//yellow
  • By passing parameters. The parameters passed are basic types, and the parameters are local variables in the function body. The parameters passed are reference types, and the parameters are global variables in the function body. It has been covered at the beginning of the article, so I won’t explain it here!

  • If a subfunction exists in the function body, only that function can access the subfunction.

var color="green";function fn(){
    //子函数是建议以下划线开头
    function _fn2(){
        var color2="orange";
        console.log(color);//green
        console.log(color2);//orange
    }
    _fn2();//_fn2()的作用域在fn()内}
fn();
_fn2();//在此处调用fn2()是调取不到的

Note: When code is executed within a scope, there is something called a scope chain. Its role is to ensure the orderliness of access to variables and methods. That is to say, if there is a specified variable or method in the current execution environment, it will not search peripherally. If it does not exist, it will search peripherally until it is found! If it cannot be found, an error will be reported! The behavior of searching for specified variables and methods layer by layer forms a chain of operations. This chain is the scope chain. Accessing local variables is much faster than global variables because there is no need to look outside (look up) for the specified variable.
* JS does not have block-level scope. The so-called block-level scope refers to the code wrapped in curly braces in if, for and other statements!

if(true){    var name="zhang";
}
console.log(name);//zhang

When you declare a variable without the var keyword in a function, the variable becomes a global variable. However, this behavior can easily cause naming conflicts, so it is not recommended for everyone to use it!

function fn(){    //此处a=12相当于window.a=12。
    a=12;//声明一个不带var关键字的变量}fn();
console.log(a);//12

This is because the fn function is run in the window environment, so a=12 in the function body is equivalent to executing window.a=12. And window is the top-level object of JS. It can also be considered that we added an attribute with a value of 12 to the top-level object. So variable a becomes a global variable.
In addition, if the variable in the function body is declared through the var keyword, the variable is a local variable and can only be accessed within the function body and cannot be accessed outside the function body.

function fn(){
    var a=12;
    console.log(a);//12}fn();
console.log(a);//报错:a is not defined
  • Share an interview question from Alibaba about scope:

var obj = {
    b: 2};var fn = function () {};
fn.c = 3;function test(x, y, z) {
    x = 4;
    y.b = 5;
    z.c = 6;    return z;
}
test(a, obj, fn);
console.log(a + obj.b + fn.c);//12
变量的生命周期

所谓变量的生命周期指的是变量由声明到销毁。
对于全局变量来讲,其生命周期是永久的,除非我们主动去销毁这个全局变量。而在函数体内声明的局部变量,当函数运行完以后,局部变量就失去了任何价值,它们也会随着函数的执行完毕而销毁。

var fn=function(){
    var a=1;//退出函数后,局部变量a会销毁
    console.log(a);
}fn();
  • JS环境中分配的内存一般有如下生命周期
    内存分配:当我们声明变量、函数、对象的时候,系统会自动为他们分配内存
    内存使用:即读写内存,也就是使用变量、函数等
    内存回收:使用完毕,由垃圾回收自动回收不再使用的内存 

  • 本文讲解了JavaScript的变量及作用域,更多相关内容请关注php中文网。

  • 相关推荐:

  • 关于$.ajax()方法参数详解

  • 讲解数学对象Math相关内容

  • 关于JS和JSP的区别讲解

The above is the detailed content of Detailed explanation of JavaScript variables and scope. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn