


Detailed explanation of js variables, scope and memory_Basic knowledge
Basic type values include: undefined, NUll, Boolean, Number and String. These types occupy a fixed size space in the memory. Their values are stored in the stack space and we access them by value.
(1) Value type: numeric 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 = "lee"; //基本类型值是字符串 box.age = 23; //基本类型值添加属性很怪异,因为只有对象才可以添加属性。 alert(box.age); //不是引用类型,无法输出; </script>
In short, the heap memory stores reference values, and the stack memory stores fixed type values.
<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 variable value
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>
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>
Javascript does not pass by reference. If there is pass by reference, then the variables within the function will be global variables and can also be accessed externally. But this is obviously impossible.
Execution environment and scope
Execution environment is one of the most important concepts in JavaScript. The execution environment defines the permissions of variables or functions to access other data.
The global execution environment is the most peripheral execution environment. In a web browser, the global execution environment is the window object. Therefore, all functions of global variables are created as properties and methods of window.
<script type="text/javascript"> var name = "Jack"; //定义全局变量 function setName(){ return "trigkit4"; } alert(window.name); //全局变量,最外围,属于window属性 alert(window.setName()); //全局函数,最外围,属于window方法 </script>
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>
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>
The function body also contains a function. 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>
Can be accessed via the following methods:
<script type="text/javascript"> var name = "Jack"; function setName(){ function setYear(){ //setYear()方法的作用域在setName()内 return 21; } return setYear(); } alert(setName()); //弹出21 </script>
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>
When code is executed in an environment, something called a scope chain will be formed. Its purpose is to ensure orderly access to variables and functions that have access rights in the execution environment (referring to the rule hierarchy). to access), the front end of the scope chain is the variable object of the execution environment.
Scope
A variable that is not declared within a function or declared without var is a global variable. It has a global scope. All properties of the window object have a global scope; it can be accessed anywhere in the code. It is declared inside the function and decorated with var. The variables are local variables and can only be used within the function body. Although the parameters of the function do not use var, they are still local variables.
No block scope
No block scope
// if语句: <script type="text/javascript"> if(true){ //if语句的花括号没有作用域的功能。 var box = "trigkit4"; } alert(box);//弹出 trigkit4 </script>
The same goes for for loop statements.
Query of variables
In variable queries, accessing local variables is faster than global variables, so there is no need to search up the scope chain.
Example below:
<script type="text/javascript"> var name = "Jack"; function setName(){ var name = "trigkit4"; return name; //从底层向上搜索变量 } alert(setName()); </script>
Memory problem
Javascript has an automatic garbage collection mechanism. Once the data is no longer used, it can be set to "null" to release the reference
Circular Reference
A very simple example: a DOM object is referenced by a Javascript object, and at the same time it references 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 a reference cycle, the object referencing the DOM element or a reference to the DOM object needs to be assigned null.
Closure
When a variable outside 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('x'); return function() { return largeStr; } }();
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('#tree'); //在COM树中leafRef是treeFre的一个子结点 var leafRef = select('#leaf'); var body = select('body'); body.removeChild(treeRef); //#tree不能被回收入,因为treeRef还在 //解决方法: treeRef = null; //tree还不能被回收,因为叶子结果leafRef还在 leafRef = null; //现在#tree可以被释放了。
Timers leaked
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; }
Debug Memory
Chrome’s built-in memory debugging tool can easily check memory usage and memory leaks:
Click record in Timeline -> Memory:

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

typedef struct is used in C language to create structure type aliases to simplify the use of structures. It aliases a new data type to an existing structure by specifying the structure alias. Benefits include enhanced readability, code reuse, and type checking. Note: The structure must be defined before using an alias. The alias must be unique in the program and only valid within the scope in which it is declared.

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

The #include preprocessor directive in C++ inserts the contents of an external source file into the current source file, copying its contents to the corresponding location in the current source file. Mainly used to include header files that contain declarations needed in the code, such as #include <iostream> to include standard input/output functions.

Advantages of JavaScript closures include maintaining variable scope, enabling modular code, deferred execution, and event handling; disadvantages include memory leaks, increased complexity, performance overhead, and scope chain effects.

According to news from this site on June 7, GEIL launched its latest DDR5 solution at the 2024 Taipei International Computer Show, and provided SO-DIMM, CUDIMM, CSODIMM, CAMM2 and LPCAMM2 versions to choose from. ▲Picture source: Wccftech As shown in the picture, the CAMM2/LPCAMM2 memory exhibited by Jinbang adopts a very compact design, can provide a maximum capacity of 128GB, and a speed of up to 8533MT/s. Some of these products can even be stable on the AMDAM5 platform Overclocked to 9000MT/s without any auxiliary cooling. According to reports, Jinbang’s 2024 Polaris RGBDDR5 series memory can provide up to 8400

According to a TrendForce survey report, the AI wave has a significant impact on the DRAM memory and NAND flash memory markets. In this site’s news on May 7, TrendForce said in its latest research report today that the agency has increased the contract price increases for two types of storage products this quarter. Specifically, TrendForce originally estimated that the DRAM memory contract price in the second quarter of 2024 will increase by 3~8%, and now estimates it at 13~18%; in terms of NAND flash memory, the original estimate will increase by 13~18%, and the new estimate is 15%. ~20%, only eMMC/UFS has a lower increase of 10%. ▲Image source TrendForce TrendForce stated that the agency originally expected to continue to

Life cycle of C++ smart pointers: Creation: Smart pointers are created when memory is allocated. Ownership transfer: Transfer ownership through a move operation. Release: Memory is released when a smart pointer goes out of scope or is explicitly released. Object destruction: When the pointed object is destroyed, the smart pointer becomes an invalid pointer.
