Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand JavaScript variable, scope and memory

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about how to understand JavaScript variables, scope and memory. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

The basic type values are: undefined,NUll,Boolean,Number and String, these types occupy a fixed amount of space in memory, and their values are stored in the stack space, which we access by value.

(1) value types: numeric, Boolean, null, undefined.

(2) reference type: object, array, function.

If you assign a value of a reference type, you must allocate space for that value in heap memory. Because the size of these 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 you can save the memory address in stack memory.

Var box = new Object (); / / create a reference type var box = "trigkit4"; / / the base type value is the string box.age = 21; / / it's weird to add attributes because only objects can add attributes. Alert (box.age); / / is not a reference type and cannot be exported

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

It is important to note here that the reference points to a specific object, not another reference.

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

Var man = new Object (); / / man points to the space address of stack memory man.name = "Jack"; var man2 = man;//man2 obtains the pointing address of man alert (man2.name); / / both pop-up Jack alert (man.name)

Copy variable valu

Take a look at the following example:

Var man = new Object (); / / man points to the space address of stack memory man.name = "Jack"; var man2 = man;//man2 gets the pointing address of man man2.name = "ming"; / / because they all point to the same object, the same name, no matter who modifies, everyone modifies alert (man2.name); / / both pop up ming alert (man.name)

It can be concluded from the above that in terms of variable replication, the basic type and the reference type are also different. The basic type copies the value itself, while the reference type copies the address.

Transfer parameters

In ECMAScript, the parameters of all functions are passed by value

Function box (num) {/ / pass num+=10; return num;} var num = 10 by value; var result = box (num); alert (result); / / if passed by reference, the num in the function will become a similar global variable, replacing alert (num) with the outer number; / / that is, * should output 20 (here 10)

Js is not passed by reference, if there is a reference, then the variables within the function will be global variables and can be accessed externally. But this is obviously impossible.

Execution environment and scope

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

The global execution environment is the outermost execution environment. In web browsers, the global execution environment is a window object, so the functions of all global variables are created as properties and methods of window.

Var name = "Jack"; / / define global variable function setName () {return "trigkit4";} alert (window.name); / / Global variable, outermost, belongs to window attribute alert (window.setName ()); / / Global function, outermost, belongs to window method

When the code in the execution environment is finished, the environment is destroyed, and the variables and functions stored in it are also destroyed. in the case of 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

Var name = "Jack"; function setName () {name = "trigkit4"; / / remove var and become a global variable} setName (); alert (name); / / pop-up trigkit4

By passing parameters, it is also a local variable

Var name = "Jack"; function setName (name) {/ / is also a local variable alert (name) by passing parameters;} setName ("pop trigkit4"); / / pop-up trigkit4 alert (name); / / pop-up Jack

The function body also contains functions, and only this function can access the functions in the inner layer.

Var name = "Jack"; function setName () {function setYear () {/ / setYear () method scope is in setName () return 21;}} alert (setYear ()); / / unable to access, error

It can be accessed by the following methods:

Var name = "Jack"; function setName () {function setYear () {/ / setYear () method scope is within setName () return 21;} return setYear ();} alert (setName ()); / / pop-up 21

Another example of scope:

Var name = "Jack"; function setName () {function setYear () {/ / setYear () method has scope in setName () var b = "hi"; / / variable b has scope in setYear () return 21;} alert (b); / / cannot be accessed}

When contemporary code is executed in an environment, something called scope chain is formed. its purpose is to ensure orderly access to variables and functions that have access in the execution environment (that is, according to the rule level). The front end of the scope chain is the variable object of the execution environment.

Scope

Variables without declaration in the function or declaration without var is a global variable, with a global scope, all properties of the window object have global scope; can be accessed anywhere in the code, the variable declared inside the function and decorated with var is a local variable, can only be used in the function body, although the parameters of the function do not use var but are still local variables.

No block-level scope

/ / if statement: the curly braces of the if (true) {/ / if statement have no scope. Var box = "trigkit4";} alert (box); / / pop-up trigkit4

The same is true of 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.

Examples are as follows:

Var name = "Jack"; function setName () {var name = "trigkit4"; return name; / / search the variable} alert (setName ()) from the bottom up

Each environment can search up the scope chain for variables and function names, but no environment can enter another execution environment by searching down the scope chain. Here, if var name = "trigkit4" is removed, "Jack" will pop up.

Memory problem

Javascript has an automatic garbage collection mechanism. Once the data is no longer in use, you can set it to "null" to release references.

Circular reference

A simple example: a DOM object is referenced by a Javascript object while referencing the same or other Javascript object, which 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 circular reference, an object that references a DOM element or a reference to a DOM object needs to be assigned to null.

Closure

When variables outside the closure are introduced into 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 leakage

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

Var select = document.querySelector

Var treeRef = select ('# tree')

/ / leafRef is a child of treeFre in the COM tree

Var leafRef = select ('# leaf')

Var body = select ('body')

Body.removeChild (treeRef)

/ / # tree cannot be returned because treeRef is still there

/ / solution:

TreeRef = null

/ / tree cannot be recycled yet, because leafRef is still there as a result of the leaves.

LeafRef = null

/ / now # tree can be released.

Leakage of Timers timer

Timers are also common places 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, just click record.

The above is the editor for you to share how to understand JavaScript variables, scope and memory, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report