Learning about variables, scopes, and memory problems in JavaScript

Source: Internet
Author: User

This is my second article on JavaScript, which has been a few years of Java development and found that JavaScript is an object-oriented language but it does have a lot of differences. In this blog, the main learning to summarize the recent learning of JavaScript, some of which are on the web, but for the understanding of JavaScript, and in the work will always be very useful, so summed up down:

Well, let's start with the variables.

There are two types of variables in javascript: One is the base type, the base type value occupies a fixed amount of space in memory, and therefore is stored in the stack memory. Copying a base type value from one variable to another creates a copy of the value. The other type is the reference type, the value of the reference type is the object, and the reference to the object is saved in the heap memory. Variables that contain reference type values actually contain not the object itself, but rather a pointer to the object, copy the value of the reference type from one variable to another, copy the pointer, and eventually point to the same object.

Then in the actual use to determine a value is the kind of basic type can use the TypeOf operator, and determine what a value is the reference type will need to use the instanceof operator.

Basic data types: Undefined, Null, Boolean, number, and string

Reference types: Object, Array, Date, RegExp, Function, basic wrapper type, monolithic built-in object (Gloabal, Math). For detailed usage of each type of reference type, describe it again in more detail next time.

JavaScript is an object-oriented language and also supports inheritance, but JavaScript supports inheritance and does not support interface inheritance.

JavaScript is a non-strong type of language that does not need to be strictly copied as a declaration type for a language such as Java, C, and must be assigned a value of the declared type. There are two types of values for JavaScript, so there are two places to copy, one is to copy the value of the variable, and the other is the parameter pass assignment when the method call. The base type is value replication, and reference type replication is a reference to an object.

Scope

There is no concept of block scope in JS. A declaration without var will be born into a global variable polluting the global environment. So in the actual use of the process, it is important to remember that the search for the variable var,js is a layer to search, if the search to the variable will stop searching (so the more the level of the search variable will certainly have a small impact on program performance).

Extend the scope chain

Although there are only two types of execution environments-Global and local (functions)-There are other ways to extend the scope chain. This is because some statements can temporarily add a variable object to the front end of the scope chain, and the variable object is removed after the code executes. So what's the exact story? There are two specific types:

(1), the catch block of the Try-catch statement.

(2), with statement block.

Both statements add a variable object to the front of the scope chain. For the WITH statement, the specified object is added to the scope chain. For a catch statement, a new variable object is created that contains the declaration of the object being thrown. So it is not recommended to use with caution in Try-catch and with. In strict mode, it is not available, but we have some understanding of with. Use an example to explain:

With (location) {var qs=search.substring (1); var hostname=hostname;var url=href;}

HREF and hostname are both location.hostname and Location.url.

Well, later on to the JS execution environment, JS execution Environment is very complex, I certainly can not be all clear, the following on the basis of my understanding of the simple summary of a few key points, later learned more, in the blog added to this time.

The execution environment and the global execution environment, asynchronous execution mechanism, event and callback functions, the event Loop, timers, JS garbage collection six aspects.

1. Execution environment and global execution environment

The execution environment has a global execution environment (also known as a Global environment) and a function execution environment.

Each time you enter a new environment, you create a scope chain that searches for variables and functions, which, as previously stated, are searched up and down one level.

The local environment of a function not only has access to variables in the scope of the function, but also has access to its containing (parent) environment, and even to the global environment.

There is a global environment that can access only variables and functions defined in the global environment, and cannot directly access any data in the local environment. The execution environment of a variable helps determine when memory should be freed.

2. Asynchronous execution mechanism

JavaScript is single-threaded, meaning that only one thing can be done at the same time. So all tasks need to be queued, and if one task executes slowly, it will affect the entire performance, then what does JavaScript do with it?

There are two kinds of tasks in javascript: One is a synchronous task and the other is an asynchronous task, that is, synchronous and asynchronous two kinds of tasks. A synchronization task is a task that is queued for execution on the main thread. An asynchronous task is a task that does not enter the main thread and goes into the task queue, and only the task queue notifies the main thread that an asynchronous task can be executed before it goes into the main thread execution.

The allowable mechanisms for asynchronous execution are as follows:

(1), all synchronization tasks are executed on the main thread, forming an execution stack (execution context stack).

(2), in addition to the main thread queue, there is a task queue. As long as the asynchronous task has a running result, an event is placed in the task queue.

(3), once all the synchronization tasks in the "execution stack" are completed, the system will query the "task queue", what events, which corresponding asynchronous tasks, and then end the waiting state, into the execution stack. Start execution.

(4), the main thread repeats the above (3) continuously.

The task queue is read as long as the mainline is Cheng.

3. Events and Callback functions

A task queue is a queue of events, IO devices, mouse clicks, page scrolling, and so on, to complete a task, adding an event to the task queue, indicating that the associated asynchronous task can enter the execution stack. That is, the main thread executes the queue. The main thread executes.

The so-called "callback function" (callback) is the code that will be hung up by the main thread. An asynchronous task must specify a callback function that executes the corresponding callback function when the main thread starts executing an asynchronous task.

Task queue, which waits until the main thread finishes executing the execution queue in the main thread, and then goes to the execution task queue. However, due to the "timer" function mentioned later, the main thread must first check the execution time, some time only to the specified time, to return to the main thread.

4. Event Loop

The main thread reads events from the task queue, and the process is constantly circulating, so the whole mechanism is called the event loop. The following three methods are required for a process to perform only one task to perform multiple tasks:

(1), queue. Because a process can only perform one task at a time, it has to wait until the current task is finished and then perform the subsequent tasks.

(2), new process. Create a new process using fork.

(3), new thread. Because the process is too resource-intensive, you can use a process to perform multi-tasking.

JavaScript is handled in a queued manner, but there is an always-running event loop to monitor which events need to be triggered and, if so, to notify the main thread to execute the callback function. That is, the above description 2, the asynchronous execution mechanism (3), (4) in the (3). This way the main thread reaches the task saturation when the task is many. There is no consumption of the context of multiple threads and the switching of the execution environment, as in multi-threading.

5. Timer

Understanding the above event callback task queue, then the timer this asynchronous task event, it is good to understand, that is, specify how long some code to execute. This is called the "Timer" function, which is the code that executes periodically. The timer function has settimeout () and setinterval () These two functions to complete, their internal operation mechanism is exactly the same, the difference is that the former specified code is a single execution, the latter repeated execution. The second parameter of SetTimeout () is 0, which means that the current main thread task is emptied. Executes the specified callback function immediately. This way, the time-consuming method can be settimeout into the task queue, and there is a sequencing in the task queue.

6. JS Garbage Collection

What does it mean when the implementation environment helps with garbage collection? The values that leave the scope are automatically marked as recyclable and therefore will be deleted during garbage collection.

Garbage collection is now more commonly used as "tag delete", the idea is to add a tag to the currently unused value, and then reclaim its memory.

There is also a "reference counting algorithm", the idea of which is to track the number of times all values are referenced. Before IE was in use, but now JavaScript no longer uses this algorithm because of the potential for memory leaks, and why, if there is a circular reference in the code, it will cause a leak. The garbage collector is run periodically, and if the amount of memory allocated for a variable is optimistic, the amount of recycling is quite large. If you need to clean up a lot of space. In this case, determining the event interval of garbage collection is a very important problem, the garbage collection mechanism of language coding is more convenient, but the internal mechanism is relatively complex, to ensure that less memory can make the page better performance. The best way to optimize memory consumption is to save only the necessary data for the code in execution. Once the data is no longer useful, finally releasing the reference by setting it to null is called dereferencing. This approach applies to the familiarity of most global variables and global variables. Local variables are automatically dereferenced when they leave the execution environment. Releasing a reference to a value does not mean that the memory consumed by the value is automatically reclaimed, but that the space can be reclaimed. The real purpose of dereferencing is to leave the value out of the execution environment so that the garbage collector can reclaim its space the next time.

About the operating mechanism of the javascipt I have summed up certainly not necessarily accurate comprehensive, hope in the future work and study, more understanding, so as to know it, and know its why.

Resources

JavaScript Advanced Programming

Http://www.ruanyifeng.com/blog/2014/10/event-loop.html

Learning about variables, scopes, and memory problems 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.