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

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>

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 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>

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>

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>

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, 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>

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>

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, 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>

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>

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.

Closure

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;
  }
}();

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可以被释放了。

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;
}

调试内存

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

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

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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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 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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool