variables, scopes, and memory issues in JavaScript

Source: Internet
Author: User

Variable
[1] Definition: A variable amount, which is equivalent to an indefinite data has a nickname. A variable is a container for storing information.
[2] Characteristics: JS variables are loosely typed, you can save any type of data. It is only a name that is used to hold a specific value at a specific time. Because there is no rule that defines what data type values A variable must hold, the value of the variable and its data type can change over the lifetime of the script.
[3] Variable declaration: Variables can be assigned at the time of declaration, but there is no other action, such as + =,-=, etc.

var a = 2; // is right. var a + = 2; // it's wrong. var a = 2++; // is wrong, + + can only be used for variables and cannot be used for constants

[4] Note: A variable defined with the var operator becomes a local variable in the scope that defines the variable. If you omit the var operator, you can create a global variable, but you will throw a referenceerror error in strict mode

[5]var: Variables declared with VAR are automatically added to the closest environment. If you initialize a variable without using the var declaration, the variable is automatically added to the global environment. In strict mode, initializing undeclared variables results in an error.
[6] Local variables: identifiers located in the parent environment are not used if there is an identifier with the same name in the local environment. Any code that is after the declaration of a local variable color that cannot access the global color variable if you do not use Window.color

The

identifier
[1] defines the name of the variable, function, property, or parameter of the function.
[2] Note:
[2.1] The first character must be a letter, an underscore, or a dollar sign. Other characters can be letters, underscores, dollar signs, or numbers [cannot appear underlined] the letters in the
[2.2] identifier can also include extended ASCII or Unicode alphabetic characters, which can be used in Chinese
[2.3] identifiers should be in small hump format, the first bit should be the type of data , the common identity is as follows:
Array a aitems
Boolean     B boolean biscomplete
floating point     F & nbsp FLoat fprice
function fn  function fnhandler
integer i  integer iitemcount
object o obje CT ODIV1
Regular expression    re  regexp Reemailcheck
String   s  string susername
Variable Volume v Variant vanything
[2.4] cannot use keywords, reserved words, true, false, and NULL as Identifiers
[2.5] for attributes that do not conform to the naming rules for identifiers, such as Background-color should be written as curly braces [ BackgroundColor]
[3] Identifier Resolution: Identifier parsing is the process of searching identifiers one level at a scope chain. The search process always starts at the front end of the scope chain, and then goes backward backwards until the identifier is found (if an identifier is not found, indicating that the identifier has not been declared, usually resulting in an error).
[3.1] If there is an identifier in the local environment with the same name, the identifier in the parent environment
e.g will not be used. Globally and locally with the same name identifier color, any code after the declaration of the local variable color, If you do not use Window.color, you cannot access the global color variable
[3.2]javascript engine does a good job in optimizing identifier queries, and the time difference for accessing global and local variables is negligible

Scope (also known as the execution Environment)
[Note that there is no block-level scope in]javascript
[1] Execution Environment: The execution environment defines the other data that variables or functions have access to, and determines their respective behavior. Each execution environment has a variable object associated with it. All variables and functions defined in the environment are stored in this object.
[2] Global Execution Environment:
[2.1] The global execution environment is the outermost execution environment, in a Web browser, the global execution environment is considered to be a Window object. All global variables and functions are therefore created as properties and methods of the Window object. Global execution environment is not destroyed until application exits such as closing Web pages or browsers
[2.2] A page is equivalent to a global scope. Whether it is the JS code in the page, or the external JS file referenced, will eventually follow the page in order to parse the sequence.
[3] Function Execution Environment: each function has its own execution environment, when the execution flow into a function, the function of the environment will be pushed into an environment stack, and after the function executes, the stack will pop up its environment, return control to the previous execution environment.
[4] Scope chain: Contemporary code when executed in an environment, creates a scope chain for the variable object. The role of a scope chain is to ensure an orderly access to all variables and functions that the execution environment has access to. The front end of the scope is always the variable object of the environment in which the code is currently executing. If the environment is a function, its active object is used as a variable object. The active object initially contains only one variable, the arguments object (this object does not exist in the global environment). The next variable object in the scope chain comes from the containing environment, and then the next variable object comes from the next containment environment. In this way, it continues to the global execution environment; The variable object of the global execution environment is always the last object in the scope chain.
[4.1] Scope chain features: The internal environment can access all external environments through the scope chain, but the external environment cannot access any variables and functions in the internal environment. The linkages between these environments are linear and sequential. Each environment can search up the scope chain to query for variables and function names, but any environment cannot enter another execution environment by searching down the scope chain.
[5] Extending the scope chain:
[5.1]try-catch statement: The catch block creates a new variable object that contains the declaration of the thrown Error object
[5.2]with statement: Adds the specified object to the scope chain

function BuildUrl () {    var qs = '? debug=true ';      with (location) {        var url = href + qs;    }     return URL;}

"Garbage Collection": JavaScript has an automatic garbage collection mechanism, and the execution environment is responsible for managing the memory used during code execution.
[1] garbage collection mechanism: Identify those variables that are no longer in use, and then release the memory they occupy, the garbage collector periodically performs this operation at regular intervals, or during the scheduled collection time in code execution
[2] Two strategies for garbage collection to mark useless variables
[2.1] Mark Clear, Mark "Enter Environment" and "leave environment". Values that leave the scope are automatically marked as recyclable and therefore will be deleted during garbage collection
[2.2] reference count, which keeps track of the number of times each value is referenced. When a variable is declared and a reference type value is assigned to the variable, the number of references to that value is 1, and if the same value is assigned to another variable, the number of references to that value is added to 1, instead, if the variable containing the reference to the value has another value, the number of references to that value is reduced by 1, When this value has a reference of 0 o'clock, it means there is no way to access the value again, so you can reclaim the memory space it occupies.
[2.2.1] Reference count problem: Circular Reference: Object A contains a pointer to object B, and object B also contains a pointer to object a
[2.2.2] Some of the objects in Ie:ie are not native JS objects, for example, the objects in their BOM and Dom are implemented in the form of COM objects using C + +, and the garbage collection mechanism of COM objects is the reference counting policy

var element = document.getElementById (' some_element '); var New  == myObject;

Workaround: To avoid circular references like these, it is best to manually disconnect them when you are not using them

Nullnull;    

To solve this problem, IE9 converted the BOM and Dom objects into real JS objects.


"Memory Management"
[1] main problem: The amount of available memory allocated to a Web browser is typically less than the number allocated to a desktop application, in order to prevent a system crash by running JS's Web page out of full system memory. Intrinsic constraints not only affect the allocation of memory to variables, but also affect the call stack and the number of statements that can be executed concurrently in one thread
[2] Optimization method: Only the necessary data is saved for the code in execution. Once the data is no longer useful, it is best to release its reference by setting its value to null, which is called dereferencing. This applies to the properties of most global variables and global objects and to circular reference variables, which are automatically dereferenced when they leave the execution environment.
Releasing a reference to a variable does not mean that the memory occupied by the value is automatically reclaimed. The real effect of dereferencing is to leave the value out of the execution environment so that it can be reclaimed the next time the garbage collector runs.

variables, scopes, and memory issues in JavaScript

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.