Details about js variables, scopes, and memory, and js Variables

Source: Internet
Author: User

Details about js variables, scopes, and memory, and js Variables

Basic Type values include 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, and function.

If the value is a reference value, you must allocate space for this value in the heap memory. Because the size of this value is not fixed (the object has many attributes and methods), they cannot be saved to the stack memory. However, the memory address size is fixed, so the memory address can be stored in the stack memory.

<Script type = "text/javascript"> var box = new Object (); // create a reference type var box = "lee"; // the basic type value is the string box. age = 23; // It is strange to add attributes to basic type values because only objects can add attributes. Alert (box. age); // It is not a reference type and cannot be output. </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 points to the stack memory space address man. name = "Jack"; var man2 = man; // man2 obtains the pointing address of man alert (man2.name); // Jack alert (man. name); </script>

Copy variable value

Let's look at the example below:

<Script type = "text/javascript"> var man = new Object (); // man points to the stack memory space address man. name = "Jack"; var man2 = man; // man2 obtains the address man2.name = "ming"; // because they all point to the same object, the same name, no matter who you modify, you have modified alert (man2.name); // The ming alert (man. name); </script>

We can conclude from the above: In terms of variable replication, the basic type and reference type are also different. The basic type replicates the value itself, while the reference type replicates the address.

PASS Parameters

In ECMAScript, all function parameters are passed by value,

<Script type = "text/javascript"> function box (num) {// pass num + = 10 by value; return num;} var num = 10; var result = box (num); alert (result); // if it is passed by reference, the num in the function will become a global variable, replace the number from the outside with alert (num); // That is to say, output 20 (output 10 here). </script>

Javascript is not passed by reference. If there is a reference, the variables in the function will be global variables and can 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 that variables or functions have the right to access other data.

The global execution environment is the peripheral execution environment. In a web browser, the global execution environment is a window object. Therefore, all global variable functions are created as window attributes and methods.

<Script type = "text/javascript"> var name = "Jack"; // defines the global variable function setName () {return "trigkit4";} alert (window. name); // global variable, exclusive, belongs to the alert (window. setName (); // global function, exclusive, belonging to the window method </script>

After the code in the execution environment is executed, the environment is destroyed, and the variables and functions in the environment are also destroyed. if the environment is a global environment, all programs or webpages must be destroyed.

Remove var local variables

<Script type = "text/javascript"> var name = "Jack"; function setName () {name = "trigkit4 "; // remove var and change it to a global variable} setName (); alert (name); // trigkit4 is displayed. </script>

Passing parameters is also a local variable

<Script type = "text/javascript"> var name = "Jack"; function setName (name) {// passing the parameter is also a local variable alert (name );} setName ("inclutrigkit4"); // trigkit4 alert (name) is displayed; // Jack is displayed. </script>

A function also contains a function. Only this function can access the function at the first layer.

<Script type = "text/javascript"> var name = "Jack"; function setName () {function setYear () {// The scope of the setYear () method is in setName () inner return 21 ;}} alert (setYear (); // inaccessible, error </script>

You can access the service by using the following methods:

<Script type = "text/javascript"> var name = "Jack"; function setName () {function setYear () {// The scope of the setYear () method is in setName () return 21;} return setYear ();} alert (setName (); // 21 </script>

Another example of scope:

<Script type = "text/javascript"> var name = "Jack"; function setName () {function setYear () {// The scope of the setYear () method is in setName () </script>

When the code is executed in an environment, it will form something called the scope chain, its purpose is to ensure orderly access to variables and functions with access permissions in the execution environment (access is performed at the rule level). The frontend of the scope chain is the variable object in the execution environment.

Scope

If a variable is not declared in a function or declared without var, it is a global variable. It has a global scope, and all properties of the window object have a global scope. It can be accessed anywhere in the code, variables declared inside the function and modified with var are local variables and can only be used in the function body. Although var is not used in function parameters, it is still a local variable.

No block-level scope

No block-level scope

// If statement: <script type = "text/javascript"> if (true) {// The curly braces of the if statement have no function of scope. Var box = "trigkit4";} alert (box); // trigkit4 is displayed. </script>


The same applies to for loop statements.

Variable Query

In the query of variables, accessing local variables is faster than the global variables, so you do not need to search for the scope chain up.
Example:

<Script type = "text/javascript"> var name = "Jack"; function setName () {var name = "trigkit4"; return name; // search for the variable} alert (setName () from the bottom layer. </script>

Memory problems

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

Loop reference

A simple example: a DOM object is referenced by a Javascript object, and the same or other Javascript objects are referenced at the same time. This DOM object may cause memory leakage. Reference of this DOM object will not be reclaimed by the garbage collector when the script is stopped. To break the circular reference, the reference of the DOM element object or DOM object must be assigned null.

Closure

When a variable outside the closure is introduced to the closure, the object cannot be garbage collection (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 sub-node reference cannot be recycled if it is not removed.

Var select = document. querySelector; var treeRef = select ('# tree'); // In the COM tree, leafRef is a subnode of treeFre. var leafRef = select (' # leaf '); var body = select ('body'); body. removeChild (treeRef); // # tree cannot be returned because treeRef is still in progress. // solution: treeRef = null; // tree cannot be recycled yet, because the leaf result leafRef is still in leafRef = null; // now # tree can be released.

Timers timer Leakage

The timer is also a common cause of Memory leakage:

For (var I = 0; I <90000; I ++) {var buggyObject = {callAgain: function () {var ref = this; var val = setTimeout (function () {ref. callAgain () ;}, 90000) ;}} buggyObject. callAgain (); // although you want to recycle it, timer is still buggyObject = null ;}

Debug memory

Chrome's built-in memory debugging tool allows you to conveniently view memory usage and Memory leakage:
In Timeline-> Memory, click record:


Scope of JS Variables

V2 = 80, v3 = 40

1. Both v2 and v3 are local variables defined in:
Function (){
Var v2, v3;

2. v2 = 80. When function B is called, function B directly assigns a value to the v2 outside function B. The most recent value is function a v2. Therefore, the v2 of function alert is 80.

3. Although function B assigns a value of 80 to function v3, v3 is the v3 of the parameter, not the v3 of function a. It assigns a value to parameter v3 without changing the v3 of function, so alert v3 remains unchanged, or 40

In addition, although there is some truth in the answer from the upstairs, it is only for the same person to write the same project,
In actual work development, it is common to reference js developed by multiple others, and even js developed by other companies. Therefore, similar code above is also possible. In addition, this example is of some significance for understanding the variable scope of js.

Variable scope issues in js

$. Post () Your asynchronous request has been executed to the last console. log (jsondata) before Ajax has been called. So there is no value. Believe it or not, you can change the type of your post request to synchronization.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.