Simple talk about variables, scopes, and memory problems in JavaScript _javascript tips

Source: Internet
Author: User
Tags garbage collection naming convention

Variable

[1] Definition: A variable amount, which is equivalent to a nickname for an indefinite number of data. A variable is a container for storing information.
[2] attribute: The variables in JS are loosely typed and can hold any type of data. It's just a name for holding a particular value at a particular time. Because there is no rule that defines what data type value A variable must hold, the value of a variable and its data type can change during the life of the script.
[3] Variable declaration: A variable can be assigned at the time of declaration, but cannot have other actions, such as + =, =, etc.

var a = 2;//is correct
var a + = 2;//is wrong
var a = 2++;//is wrong, + + can only be used for variables, not 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 in strict mode it throws a Referenceerror error

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

Identifier

[1] Definition: The name of a variable, function, attribute, or the parameter of a 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 [no dashes appear]
The letters in the [2.2] identifier can also include extended ASCII or Unicode alphabetic characters, which can be used in Chinese
[2.3] The identifier should be in small hump format, the first digit should be the type of data, the common identification is as follows:

Array A-array aitems
Boolean  b boolean biscomplete
floating-point number  f float fprice
function fn Function fnhandler
integer i iitemcount
object O-Object oDIv1
Regular expression  re RegExp re Emailcheck
Strings  s string susername
variable v variant vanything 

[2.4] You cannot use keywords, reserved words, true, false, and NULL as identifiers
[2.5] Properties such as Background-color should be written as curly braces for attributes that do not conform to an identifier naming convention [BackgroundColor]
[3] Identifier Resolution: Identifier resolution is the process of searching for identifiers one level along the scope chain. The search process always starts at the front end of the scope chain, and then goes backwards back and forth until the identifier is found (if the identifier is not found, the identifier is not yet declared and usually results in an error).
[3.1] The identifier in the parent environment is not used if there is an identifier in the local environment with the same name
e.g. global and local have the identifier color of the same name, any code after the declaration of the local variable color, and you cannot access the global color variable without using Window.color
[3.2] JavaScript engines do a good job of optimizing identifier queries, and the time difference between accessing global and local variables can be negligible

"Scope" (also known as execution environment)

[Note that there is no block-level scope in]javascript
[1] Execution Environment: The execution environment defines other data that a variable or function has access to, determining their respective behavior. Each execution environment has a variable object associated with it. All variables and functions defined in the environment are saved in this object.

[2] Global Execution Environment:
[2.1] The global execution environment is the outermost execution environment in which the global execution environment is considered a Window object. Therefore, all global variables and functions are created as properties and methods of the Window object. The global execution environment will not be destroyed until the application exits, such as closing a Web page or browser
[2.2] A page is equivalent to a global scope. Whether it is a page of JS code, or a reference to the external JS file, will eventually follow the page in the sequence of the resolution.

[3] Function Execution Environment: each function has its own execution environment, when the execution flow enters a function, the function environment will be pushed into an environment stack, and after the function executes, the stack will eject its environment and return control to the previous execution environment.

[4] Scope chain: When a contemporary code executes in an environment, it creates a scope chain of variable objects. The role of a scope chain is to ensure orderly access to all variables and functions that have access to the execution environment. The front end of the scope is always the variable object of the environment in which the currently executing code resides. If the environment is a function, its active object is treated as a variable object. The active object contains only one variable at the beginning, that is, 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 the next variable object comes from the next containing environment. This continues to the global execution environment, and the variable object of the global execution environment is always the last object in the scope chain.

[4.1] The characteristics of the scope chain: 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 connections between these environments are linear and sequential. Each environment can search the scope chain up to query for variables and function names, but no environment could enter another execution environment by searching the scope chain down.

[5] Extend the scope chain:

[5.1]try-catch statement: a catch block creates a new variable object that contains the declaration of the wrong object being thrown
[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 automated garbage collection mechanism, which 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, which is periodically performed by the garbage collector at regular intervals, or during scheduled collection times in code execution

[2] Two strategies of garbage collection tag useless variables

[2.1] Mark Clears, marking "Enter the environment" and "leave the environment". The value leaving the scope is automatically marked as recyclable and will be deleted during garbage collection
[2.2] reference count, which tracks 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 this value is 1, and if the same value is assigned to another variable, the reference number of that value is 1, and conversely, if the variable containing the reference to the value gets another value, the reference number of that value is reduced by 1. When the number of references to this value is 0 o'clock, there is no way to access the value again, so you can reclaim the memory space it occupies.
Problem with [2.2.1] reference count: 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, their BOM and DOM objects are implemented using C + + as a COM object, and the garbage collection mechanism of COM objects is a reference-counting policy

var element = document.getElementById (' some_element ');
var myObject = new Object ();
Myobject.element = element;
Element.someobject = MyObject;

WORKAROUND: To avoid such circular references, it is best to manually disconnect them without using them

Myobject.element = null;
Element.someobject = null;
To solve this problem, IE9 transforms the BOM and Dom objects into real JS objects.

"Memory Management"

[1] The main problem: The amount of available memory allocated to a Web browser is typically less than that allocated to a desktop application, in order to prevent the system from running out of all system memory and causing a crash. Internal constraints not only affect allocating 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 a dereference. This applies to the properties of most global variables and global objects, as well as to circular reference variables, which are automatically dereference when they leave the execution environment.

Removing a reference to a variable does not automatically reclaim the memory occupied by the value. The real purpose of the dereference is to leave the value out of the execution environment so that the garbage collector will recycle it the next time it runs.

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.