Js scope Chain & memory reclaim & Variable & Closure

Source: Internet
Author: User

Js scope Chain & memory reclaim & Variable & Closure

Closure mainly involves several other features of js: Scope chain, garbage (memory) collection mechanism, function nesting, etc.

I. Scope chain: an index created when a function is defined and used to find the value of the used variable. Its internal rule is, put the local variables of the function itself at the beginning, put the variables in its parent-level functions at the second place, put the variables in the higher-level functions at the back, and so on until the global object ends. when a function needs to query the value of a variable, the js interpreter searches for the value in the scope chain first from the local variable at the beginning. If the corresponding variable is not found, find the variable on the chain at the next level. Once the variable is found, it will not continue. if no variable is found, the interpreter returns undefined.

Ii. Memory recycling mechanism: When a function is executed, it will divide the defined variable volume into memory space for storage for subsequent statements. After the function is executed, it will return, these variables are considered useless. the corresponding memory space is recycled. when you execute this function next time, all the variables return to the initial state, and the values are assigned again. however, if another function is nested inside the function, this function may be called externally. and the internal function uses some variables of the external function. this memory recovery mechanism will cause problems. if an internal function is directly called after an external function is returned, the internal function cannot read the value of the variable in the required external function. therefore, when the js interpreter encounters a function definition, it will automatically include the function and its possible variables (including the local variables and the variables of the parent and ancestor functions (free variables )) save them together. it is to build a closure, and these variables will not be recycled by the memory recycler. Only when the internal function cannot be called (for example, deleted or no pointer ), will destroy this closure, without any closure The variables used will be recycled at the next memory recycle startup.

3. Local variables & global variables

1. global) the scope of a variable is global and is defined everywhere in Javascript. The variable declared in the function is a local variable, and its scope is local, this variable is defined only within the function body and will be created and destroyed each time the function is executed.

2. You do not need to use the var statement when using a variable in the global variable scope. However, when declaring a local variable, you must use the var statement. Otherwise, it will be considered as a reference to the global variable.

3,

Var scope = "local ";The declared variables are valid throughout the scope of the checkScope function. Therefore, the firstDocument. write (scope );During execution, scope references local variables, but the local variable scope is not defined yet, so "undefined" is output ". A good programming habit is to put all the variable declarations together at the beginning of the function. Document. write (window. scope) // output global

Global variables always exist at the end of the context scope chain at runtime. Therefore, when the identifier is parsed, It is the slowest to search for global variables. Therefore, when writing code, use global variables as little as possible and use local variables as much as possible. A good rule of thumb is: if a cross-scope object is referenced more than once, it is first stored in a local variable before being used (document, window, etc ).

When executing JavaScript code, an identifier is searched in the scope chain of Execution Context according to the identifier name. From the first Object in the scope chain to the Activation Object of the function), if not found, search for the next Object in the scope chain until the identifier definition is found. If the last Object in the search scope, that is, the Global Object, is not found, an error is thrown, prompting the user to undefined the variable ). This is the process of parsing Identifier Resolution in the function execution model and Identifier described in the ECMA-262 standard.

Defined by the third edition of the ECMA-262 standard, this internal attribute contains a set of objects in the scope of the function being created, a collection called the function's scope chain, which determines which data can be accessed by the function. The first object in the scope is always the variable object in the environment where the code is currently executed.

Function a (x, y ){

Var B = x + y;

Return B;

}

When function a is created, its scope chain is filled with global objects, which contain all global variables.

Var tatal = a (5, 10 );

When this function is executed, an internal object called "execution context" is created, and the runtime context defines the environment when the function is executed. Values are copied to the scope chain of the runtime context in the order they appear in the function. They form a new object called the activation object. this object contains all the local variables, named parameters, parameter sets, and this of the function, the object is then pushed to the front end of the scope chain. When the context is destroyed during the runtime, the activity object is also destroyed.

The ECMAScript variable may contain two different data types: basic type value and reference type value. The basic type value refers to the simple data segments stored in the stack memory, that is, the values are completely stored in a location in the memory. The reference type value refers to the objects in the heap memory. It means that the objects stored in the variable are actually just a pointer. This Pointer Points to another location in the memory, where the objects are saved.

Five basic data types: Undefined, Null, Boolean, Number, and String. The values of these five basic data types occupy a fixed space in the memory, so they can be stored in the stack memory.

If a value of the reference type is assigned to the variable, space must be allocated for the value in the heap memory. Because the size of such values is not fixed, they cannot be saved to the stack memory. However, the size of the memory address is fixed, so the memory address can be stored in the stack memory. In this way, when querying referenced variables, You can first read the memory address from the stack, and then find the value saved in the heap.

Each value stored in the stack memory occupies a fixed space and can be accessed in order. If the stack memory stores a memory address, the value is like a pointer pointing to the object's position in the heap memory. Data stored in the heap memory is not accessed sequentially because the space required by each object is not equal.

When a value of the reference type is copied from one variable to another, the value stored in the stack is also copied to the space allocated for the new variable. The difference is that,The copy of this value is actually a pointer, and this pointer points to an object stored in the heap. After the copy operation is complete, the two variables actually reference the same object.Therefore, changing one of the variables will affect another variable.

The typeof operator is the best tool for determining whether a variable is a string, value, Boolean value, or undefined basic data type. When detecting the value of the reference type, ECMAScript providesInstanceof operator.

Iv. Closure

As long as the call to internal functions is possible, JavaScript needs to retain the referenced functions. In addition, when JavaScript is running, it is necessary to trace all variables that reference this internal function. Until the last variable is discarded, the JavaScript Garbage Collector can release the corresponding memory space. The red part is the key to understanding the closure ).

Closure has two major functions: one is to read the internal variables of the function, and the other is to keep the values of these variables in the memory.

 

Notes for using closures

1) because the closure will make the variables in the function be stored in the memory, the memory consumption is very large, so the closure cannot be abused, otherwise it will cause the performance of the web page, memory leakage may occur in IE. The solution is to delete all unused local variables before exiting the function.

2) The closure changes the value of the internal variable of the parent function outside the parent function. Therefore, if you use the parent function as an object), use the closure as its Public Method), and use the internal variable as its private property private value ), be sure not to change the value of the internal variable of the parent function.

Examples of closures:

Related Article

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.