JS scope chain & Memory Reclaim & variables & Closures

Source: Internet
Author: User

Closures mainly involve several other features of JS: Scope chain, garbage (memory) recycling mechanism, function nesting, and so on.Scope Chain: The function is created at the time of definition, used to find an index of the value of the variable used, and his internal rule is to put the local variables of the function itself in the first place, put the variables in the parent function in the second, put the variables in the higher-level function later, And so on until the global object. When the function needs to query the value of a variable, the JS interpreter will go to the scope chain to find, from the first local variables to find, if not found the corresponding variable, then to the next level of the chain to find, once the variable is found, it will no longer continue. If you find the last variable , the interpreter returns undefined. TwoMemory recovery mechanism: A function at the beginning of the execution, the variables defined in the memory space to save, in case of the subsequent statements to use, wait until the function has been executed to return, these variables are considered useless. The corresponding memory space is also recycled. The next time you execute this function, all the variables go back to their original state. Re-assign the value to use. But if another function is nested inside the function, it is possible that the function is called externally. And this internal function uses some variables of the external function. This memory-recycling mechanism can cause problems. If an intrinsic function is called directly after the external function returns, the Then the intrinsic function cannot read the value of the variable in the external function that he needs. So the JS interpreter will automatically save the function and the variables he or she may use, including the local variables and the variables (free variables) of the parent and ancestor-level functions, when it encounters the function definition. That is, to build a closure, These variables will not be reclaimed by the memory collector, but only if the internal function is not possible to be called (for example, if it is deleted, or if there is no pointer), the closure will be destroyed, and no one of the closure references will be recycled when the next memory recycle starts. ThreeLocal Variables & global variables1. Global variables are globally scoped and defined everywhere in JavaScript, whereas variables declared inside a function are local (local) variables whose scope is local and are defined only within the body of the function, and are created and destroyed each time the function is executed. 2. Variables can be used in a global variable scope without a var statement, but it is important to use the VAR statement when declaring a local variable, otherwise it is considered a reference to a global variable. 3. var scope = "local";Declared variables are valid throughout the scope of the Checkscope function, so the first document.write (scope);When executed, scope refers to a local variable, and the local variable scope is not defined at this time, so the output is "undefined". 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 run-time context chain, so finding global variables is the slowest when identifiers are resolved. Therefore, when writing code, you should use as few global variables as possible, using local variables as much as you can. A good rule of thumb is that if a cross-scope object is referenced more than once, it is stored in a local variable for reuse (document, window, and so on).   During the execution of JavaScript code, when an identifier is encountered, it is searched in the scope chain of the execution context (execution contexts) based on the name of the identifier. Starts from the first object of the scope chain (the function's activation object) and, if it is not found, searches for the next object in the scope chain, and so on, until the definition of the identifier is found. If it is not found after the last object in the scope, that is, the global object, an error is thrown that prompts the user that the variable is undefined (undefined). This is the process of performing model and identifier resolution (Identifier Resolution) for functions described in the ECMA-262 standard.   is defined by the ECMA-262 Standard third edition, which contains a collection of objects within the scope of the function being created, called the scope chain of the function, which determines which data can be accessed by the function. Scope The first object is always the variable object in the environment where the current execution code is located function a (x, y) {     var b=x+y;      return b;} When function A is created, its scope chain fills the global object, with all global variables var tatal=a (5,10) in the global object, and an internal object called run-time context (execution context) is created when this function is executed. The run-time context defines the environment at which the function executes. Values are copied into the scope chain of the run-time context, in the order in which they appear in the function. Together they form a new object called the "Activation Object", which contains all the local variables, named arguments, parameter collections, and this for the function, and then this object is pushed into the front end of the scope chain, when the run-timeThe context is destroyed and the active object is destroyed. The ECMAScript variable may contain values for two different data types: the base type value and the reference type value. Primitive type values refer to simple data segments that are stored in the stack's memory, meaning that this value is completely stored in a single location in memory. Reference-type values are those that hold objects in the heap memory, meaning that the variables are actually just a pointer to another location in memory where the object is saved. 5 Basic data types: Undefined, Null, Boolean, number, and string. The values of these 5 basic data types occupy a fixed amount of space in memory, so they can be stored in the stack memory. If you assign a value to a variable that is a reference type, you must allocate space for the value in heap memory. Because the size of this value 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. Thus, when querying a variable of a reference type, it is possible to first read the memory address from the stack and then "trace" the value stored in the heap. Each value stored in the stack memory occupies a fixed size of space, which can be accessed sequentially. If the stack memory holds a memory address, this value is like a pointer to the object's location in the heap memory. Data that is stored in heap memory is not accessed sequentially because the space required for each object is not equal. When a value of a reference type is copied from one variable to another, the value stored in the stack is also copied into the space allocated for the new variable. The difference is that A copy of this value is actually a pointer to an object stored in the heap. When the copy operation is finished, two variables will actually refer to the same object. Therefore, changing one of the variables will affect the other. The typeof operator is the best tool for determining whether a variable is a string, a numeric value, a Boolean, or a undefined base data type. When a value of a reference type is detected, ECMAScript provides a The instanceof operator. four, closed package as long as there is the possibility of invoking an intrinsic function, JavaScript needs to preserve the referenced function. and the JavaScript runtime needs to keep track of all the variables that reference this intrinsic function until the last variable is discarded, and the JavaScript garbage collector frees up the corresponding memory space (the red part is the key to understanding closures). The maximum use of closures is two, one is to read the variables inside the function, and the other is to keep the values of these variables in memory at all times. note points for using closures1) Because the closure will make the variables in the function are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page, in IE may cause memory leaks. The workaround is to remove all unused local variables before exiting the function. 2) The closure changes the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, and the closure as its public method, and the internal variable as its private property (private value), be careful not to arbitrarily change the value of the inner variable of the parent function. Closures Some examples: The above code will be executed after the page load, when the value of I is 4, the judgment condition is not established, the For loop executes, but because the onclick method of each span is an intrinsic function, so I is referenced by the closure, memory can not be destroyed, I value will remain 4, It will not be recycled until the program changes it or all of the onclick functions are destroyed (by actively assigning the function null or page unloading). So every time we click on span, the onclick function looks for the value of I (the scope chain is the reference method), and a check equals 4.

JS scope chain & Memory Reclaim & variables & Closures

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.