search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript variables and scope

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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool