Table of Contents
Copy variable values
Pass parameters
Execution environment and scope
Remove the local variable of var
By passing parameters, it is also a local variable
" >Closure
调试内存
Home Web Front-end JS Tutorial Detailed explanation of JavaScript variables, scope and memory

Detailed explanation of JavaScript variables, scope and memory

Mar 04, 2017 pm 04:02 PM
javascript

The basic type values ​​are: undefined, NUll, Boolean, Number and String. These types occupy a fixed size space in the memory, and their values ​​are stored in the stack space. We access it by value.

(1) Value type: numerical value, Boolean value, null, undefined.
(2) Reference type: object, array, function.

If the value assigned is a reference type, space must be allocated for this value in heap memory. Since the size of such values ​​is not fixed (objects have many properties and methods), they cannot be saved to stack memory. But the memory address size is fixed, so the memory address can be saved in stack memory.

<script type="text/javascript”>
var box = new Object();  //创建一个引用类型
var box = "trigkit4";   //基本类型值是字符串
box.age = 21;    //基本类型值添加属性很怪异,因为只有对象才可以添加属性。
alert(box.age);  //不是引用类型,无法输出;
</script>
Copy after login

In short, the heap memory stores reference values, and the stack memory stores fixed type values. A "reference" is a pointer to the actual location of an object.

It should be noted here that the reference points to a specific object, not another reference.

The objects here can be string objects, numeric objects, array objects, etc.

<script type="text/javascript">
    var man = new Object();//man指向了栈内存的空间地址
    man.name = "Jack";
    var man2 = man;//man2获得了man的指向地址

    alert(man2.name);//两个都弹出Jack
    alert(man.name);
</script>
Copy after login

Copy variable values

Look at the following Example:

<script type="text/javascript">
    var man = new Object();//man指向了栈内存的空间地址
    man.name = "Jack";
    var man2 = man;//man2获得了man的指向地址

    man2.name = "ming";//因为他们都指向同一个object,同一个name,不管修改谁,大家都修改了
    alert(man2.name);//两个都弹出ming
    alert(man.name);
</script>
Copy after login

It can be concluded from the above: in terms of variable copying, basic types and reference types are also different. Basic types copy the value itself, while reference types copy the address.

Pass parameters

In ECMAScript, all function parameters are passed by value,

<script type="text/javascript">
     function box(num){      //按值传递
         num+=10;
         return num;
     }

     var num = 10;
     var result = box(num);
     alert(result);  //如果是按引用传递,那么函数里的num会成为类似全局变量,把外面的number替换掉
     alert(num);    //也就是说,最后应该输出20(这里输出10)
</script>
Copy after login

js are not passed by reference, if they exist If passed by reference, the variables within the function will be global variables and can also be accessed externally. But this is obviously impossible.

Execution environment and scope

The execution environment is one of the most important concepts in javascript. The execution environment defines the variables or functions that have access to other data.

The global execution environment is the most peripheral execution environment. In a web browser, the global execution environment is a window object. Therefore, all functions of global variables are used as window Created by the properties and methods of .

<script type="text/javascript">
      var name = "Jack";           //定义全局变量
      function setName(){
          return "trigkit4";
      }

      alert(window.name);        //全局变量,最外围,属于window属性
      alert(window.setName());  //全局函数,最外围,属于window方法
</script>
Copy after login

When the code in the execution environment is executed, the environment is destroyed, and the variables and functions saved in it are also destroyed. If it is a global environment, it will not be destroyed until all programs have been executed or the web page has been completed. .

Remove the local variable of var

<script type="text/javascript">
      var name = "Jack";
      function setName(){
          name = "trigkit4";   //去掉var变成了全局变量
      }

      setName();
      alert(name);//弹出trigkit4
</script>
Copy after login

By passing parameters, it is also a local variable

<script type="text/javascript">
      var name = "Jack";
      function setName(name){    //通过传参,也是局部变量
          alert(name);
      }

      setName("trigkit4");//弹出trigkit4
      alert(name);//弹出Jack
</script>
Copy after login

The function body also contains a function, and only this function can access the inner layer of functions

<script type="text/javascript">
     var name = "Jack";
      function setName(){
          function setYear(){    //setYear()方法的作用域在setName()内
              return 21;
          }
      }
      alert(setYear());//无法访问,出错 
</script>
Copy after login

can be accessed through the following methods:

<script type="text/javascript">
     var name = "Jack";
      function setName(){
          function setYear(){    //setYear()方法的作用域在setName()内
              return 21;
          }
          return setYear();
      }
      alert(setName()); //弹出21
</script>
Copy after login

Another scope example:

<script type="text/javascript">
     var name = "Jack";
      function setName(){
          function setYear(){    //setYear()方法的作用域在setName()内
              var b = "hi";     //变量b的作用域在setYear()内
              return 21;
          }
          alert(b);//无法访问 
      }
</script>
Copy after login

When code is executed in an environment, a type of code called # will be formed. ##Scope chain is used to ensure orderly access to variables and functions that have access rights in the execution environment (referring to access according to the rule level). The front end of the scope chain is the execution environment variable object.

Scope

The variable is not declared within the function or is declared without

varIt is a global variable, has a global scope, windowobject All attributes have global scope; they can be accessed anywhere in the code. Variables declared inside the function and modified with var are local variables and can only be used within the function body. Although the function parameters do not use varBut it is still a local variable.

No block-level scope

// if语句:

<script type="text/javascript">
if(true){                        //if语句的花括号没有作用域的功能。

var box = "trigkit4";
}
alert(box);//弹出 trigkit4
</script>
Copy after login

The same is true for for loop statements.

Variable query

In variable query, accessing local variables is faster than global variables, so there is no need to search up the scope chain.

The following example:

<script type="text/javascript">
     var name = "Jack";
      function setName(){
           var name = "trigkit4";
           return name;  //从底层向上搜索变量
    }
    alert(setName());      
</script>
Copy after login

Each environment can search up the scope chain to query variable and function names; but no environment can enter another by searching down the scope chain. execution environment. Here, if you remove

var name = "trigkit4", then "Jack" will pop up

Memory problem

javascriptHas an automatic garbage collection mechanism , once the data is no longer used, you can set it to "null" to release the reference

Circular reference

A very simple example: a DOM object is replaced by a

Javascript Object reference, while referencing the same or other Javascript object, this DOM object may cause a memory leak. The reference to this DOM object will not be reclaimed by the garbage collector when the script stops. To break the circular reference, the object referencing the DOM element or the reference to the DOM object needs to be assigned the value null.

When a variable external to the closure is introduced in the closure, the object cannot be garbage collected (GC) when the closure ends.

var a = function() {
  var largeStr = new Array(1000000).join(&#39;x&#39;);
  return function() {
    return largeStr;
  }
}();
Copy after login

DOM leak

When the original COM is removed, the child node reference cannot be recycled unless it is removed.

var select = document.querySelector;
var treeRef = select(&#39;#tree&#39;);

//在COM树中leafRef是treeFre的一个子结点
var leafRef = select(&#39;#leaf&#39;); 
var body = select(&#39;body&#39;);

body.removeChild(treeRef);

//#tree不能被回收入,因为treeRef还在
//解决方法:
treeRef = null;

//tree还不能被回收,因为叶子结果leafRef还在
leafRef = null;

//现在#tree可以被释放了。
Copy after login

Timers timer leak

Timers are also a common place where memory leaks occur:

for (var i = 0; i < 90000; i++) {
  var buggyObject = {
    callAgain: function() {
      var ref = this;
      var val = setTimeout(function() {
        ref.callAgain();
      }, 90000);
    }
  }

  buggyObject.callAgain();
  //虽然你想回收但是timer还在
  buggyObject = null;
}
Copy after login

调试内存

Chrome自带的内存调试工具可以很方便地查看内存使用情况和内存泄露,在 Timeline -> Memory 点击record即可。

以上就是JavaScript 变量、作用域及内存详解的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
Large memory optimization, what should I do if the computer upgrades to 16g/32g memory speed and there is no change? Large memory optimization, what should I do if the computer upgrades to 16g/32g memory speed and there is no change? Jun 18, 2024 pm 06:51 PM

For mechanical hard drives or SATA solid-state drives, you will feel the increase in software running speed. If it is an NVME hard drive, you may not feel it. 1. Import the registry into the desktop and create a new text document, copy and paste the following content, save it as 1.reg, then right-click to merge and restart the computer. WindowsRegistryEditorVersion5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\MemoryManagement]"DisablePagingExecutive"=d

How to check memory usage on Xiaomi Mi 14Pro? How to check memory usage on Xiaomi Mi 14Pro? Mar 18, 2024 pm 02:19 PM

Recently, Xiaomi released a powerful high-end smartphone Xiaomi 14Pro, which not only has a stylish design, but also has internal and external black technology. The phone has top performance and excellent multitasking capabilities, allowing users to enjoy a fast and smooth mobile phone experience. However, performance will also be affected by memory. Many users want to know how to check the memory usage of Xiaomi 14Pro, so let’s take a look. How to check memory usage on Xiaomi Mi 14Pro? Introduction to how to check the memory usage of Xiaomi 14Pro. Open the [Application Management] button in [Settings] of Xiaomi 14Pro phone. To view the list of all installed apps, browse the list and find the app you want to view, click on it to enter the app details page. In the application details page

Is there a big difference between 8g and 16g memory in computers? (Choose 8g or 16g of computer memory) Is there a big difference between 8g and 16g memory in computers? (Choose 8g or 16g of computer memory) Mar 13, 2024 pm 06:10 PM

When novice users buy a computer, they will be curious about the difference between 8g and 16g computer memory? Should I choose 8g or 16g? In response to this problem, today the editor will explain it to you in detail. Is there a big difference between 8g and 16g of computer memory? 1. For ordinary families or ordinary work, 8G running memory can meet the requirements, so there is not much difference between 8g and 16g during use. 2. When used by game enthusiasts, currently large-scale games basically start at 6g, and 8g is the minimum standard. Currently, when the screen is 2k, higher resolution will not bring higher frame rate performance, so there is no big difference between 8g and 16g. 3. For audio and video editing users, there will be obvious differences between 8g and 16g.

Sources say Samsung Electronics and SK Hynix will commercialize stacked mobile memory after 2026 Sources say Samsung Electronics and SK Hynix will commercialize stacked mobile memory after 2026 Sep 03, 2024 pm 02:15 PM

According to news from this website on September 3, Korean media etnews reported yesterday (local time) that Samsung Electronics and SK Hynix’s “HBM-like” stacked structure mobile memory products will be commercialized after 2026. Sources said that the two Korean memory giants regard stacked mobile memory as an important source of future revenue and plan to expand "HBM-like memory" to smartphones, tablets and laptops to provide power for end-side AI. According to previous reports on this site, Samsung Electronics’ product is called LPWide I/O memory, and SK Hynix calls this technology VFO. The two companies have used roughly the same technical route, which is to combine fan-out packaging and vertical channels. Samsung Electronics’ LPWide I/O memory has a bit width of 512

Samsung announced the completion of 16-layer hybrid bonding stacking process technology verification, which is expected to be widely used in HBM4 memory Samsung announced the completion of 16-layer hybrid bonding stacking process technology verification, which is expected to be widely used in HBM4 memory Apr 07, 2024 pm 09:19 PM

According to the report, Samsung Electronics executive Dae Woo Kim said that at the 2024 Korean Microelectronics and Packaging Society Annual Meeting, Samsung Electronics will complete the verification of the 16-layer hybrid bonding HBM memory technology. It is reported that this technology has passed technical verification. The report also stated that this technical verification will lay the foundation for the development of the memory market in the next few years. DaeWooKim said that Samsung Electronics has successfully manufactured a 16-layer stacked HBM3 memory based on hybrid bonding technology. The memory sample works normally. In the future, the 16-layer stacked hybrid bonding technology will be used for mass production of HBM4 memory. ▲Image source TheElec, same as below. Compared with the existing bonding process, hybrid bonding does not need to add bumps between DRAM memory layers, but directly connects the upper and lower layers copper to copper.

Micron: HBM memory consumes 3 times the wafer volume, and production capacity is basically booked for next year Micron: HBM memory consumes 3 times the wafer volume, and production capacity is basically booked for next year Mar 22, 2024 pm 08:16 PM

This site reported on March 21 that Micron held a conference call after releasing its quarterly financial report. At the conference, Micron CEO Sanjay Mehrotra said that compared to traditional memory, HBM consumes significantly more wafers. Micron said that when producing the same capacity at the same node, the current most advanced HBM3E memory consumes three times more wafers than standard DDR5, and it is expected that as performance improves and packaging complexity intensifies, in the future HBM4 This ratio will further increase. Referring to previous reports on this site, this high ratio is partly due to HBM’s low yield rate. HBM memory is stacked with multi-layer DRAM memory TSV connections. A problem with one layer means that the entire

Installed memory not showing up on Windows 11 Installed memory not showing up on Windows 11 Mar 10, 2024 am 09:31 AM

If you have installed new RAM but it is not showing up on your Windows computer, this article will help you resolve the issue. Usually, we improve the performance of the system by upgrading RAM. However, system performance also depends on other hardware such as CPU, SSD, etc. Upgrading RAM can also improve your gaming experience. Some users have noticed that installed memory is not showing up in Windows 11/10. If this happens to you, you can use the advice provided here. Installed RAM not showing up on Windows 11 If the installed RAM is not showing up on your Windows 11/10 PC, the following suggestions will help you. Is the installed memory compatible with your computer's motherboard? in BIO

Lexar launches Ares Wings of War DDR5 7600 16GB x2 memory kit: Hynix A-die particles, 1,299 yuan Lexar launches Ares Wings of War DDR5 7600 16GB x2 memory kit: Hynix A-die particles, 1,299 yuan May 07, 2024 am 08:13 AM

According to news from this website on May 6, Lexar launched the Ares Wings of War series DDR57600CL36 overclocking memory. The 16GBx2 set will be available for pre-sale at 0:00 on May 7 with a deposit of 50 yuan, and the price is 1,299 yuan. Lexar Wings of War memory uses Hynix A-die memory chips, supports Intel XMP3.0, and provides the following two overclocking presets: 7600MT/s: CL36-46-46-961.4V8000MT/s: CL38-48-49 -1001.45V In terms of heat dissipation, this memory set is equipped with a 1.8mm thick all-aluminum heat dissipation vest and is equipped with PMIC's exclusive thermal conductive silicone grease pad. The memory uses 8 high-brightness LED beads and supports 13 RGB lighting modes.

See all articles