Interview must be a problem, what is the closure of what is the use, feel that their previous answer is not good, so this review of the Red Book when summed up.
Mention closures, the relevant knowledge points are more, so the first list of what to say.
1. scope chain, active object
2. about this object
3. garbage collection mechanism, memory leaks
4. impersonation of block-level scopes, private variables
The content involved so much, it is no wonder that the interviewer likes to ask this question ah, like Niko Big God said, should be based on the depth of the answer to understand your mode of thinking it. No more nonsense, start to get to the point.
1. scope chain, active object
Active object: the active object is the first time the function is called, an object is created, which is mutable at the time of the function, and contains this,arguments, as well as local variables and named parameters.
execution Environment: The execution environment defines the other data that a variable or function has access to, and determines their respective behavior. Each execution environment has a variable object associated with it, and all variables and functions defined in the environment are stored in the object. After the code in an execution environment is executed, the environment is destroyed and all the variables and functions stored therein are destroyed. Ah said genteel, I according to their own understanding of the vernacular a good. Simply put, every function that starts calling execution creates an execution environment, which is the same as the scope in C, which is the variable you can access during the execution of the function. Data ah those will be placed in an environment stack, some of the data you can access, no of course can not access, when you have done, Just pop you out of the environment stack, the execution environment is destroyed, you can not visit ~ ~ ~
Scope Chain: is an ordered access to all variables and functions that have access to the execution environment. The front end of the scope chain, which is always the variable object in the environment where the current execution code is located, is the global variable at the end. This is also very well understood, in the execution of the function to access a variable, at the beginning of the search in the current environment there is no such variable, no words in the search for the function outside the variable has no, so layer up to look up, and finally back to the global variable. Therefore, if the prototype chain is very long, the property value of the prototype will look long and grey.
closure: A function that has access to a variable in another function scope. The common way to create closures is to create another function inside one function.
So many nouns are mentioned earlier, so let's string it out what happens when the function is first called?
At the first call of the function, create an execution environment and a corresponding scope chain, and the main scope chain value is paid to a special internal property ([[scope]]). The active object of the function is then initialized with the values of this,arguments and other named parameters. In the scope chain, the active object of the current function is first, the active object of the outer function is in the second position, and the outer outer active object is in the third place ... The scope chain focuses on the global execution environment.
When creating a function I, create a scope chain containing the global variable object, which is stored in the internal [[scope]] property. When the function is called, an execution environment is created for the function, and the scope chain of the execution environment is built from the object in the [scope] property of the copy function. Thereafter, another active object (variable object) is created and pushed into the front end of the execution environment scope chain. The scope chain consists of two variable objects: The local active object and the global variable object. A scope chain is essentially a list of pointers to variable objects that reference but do not contain actual variable objects.
What is the difference between closures and normal functions?
After the normal function is executed, the local activity is destroyed and only the global scope is saved in memory. But closures are different, and when the outer function of a closure is executed, its active object is not destroyed, because the scope chain of its anonymous function is thrown in to reference the active object. So even if the scope chain of the external function execution environment is destroyed, its active object is still in memory until the anonymous function is destroyed.
Closures and variables: because the scope chain is essentially a pointer to a variable object list, it only references but does not contain the actual variable object, so the closure can only get the last value in the containing function. A closure holds the entire variable object, not the value of a particular variable. Here is a small example.
function Createfunctions () {
var result = new Array ();
for (var i = 0; i < i++) {
Result[i] = function () {
return i;
};
}
return result;
}
This function returns an array of functions. The expectation is that this function returns [0~9] after each function is executed, and the reality is always so brutal that the return is [10......10]. Because the active objects of createfunctions () are kept in the scope chain of each function in the array, they refer to the same variable i. When the Createfunctions () function returns, the value of the variable i is 10, and each function refers to the same variable i = 10, so each function of the function array returns 10.
The revised version of the 2.0 follows:
function Createfuncs () {
var result = new Array ();
for (Var i=0;i<10;i++) {
Result[i] = function (num) {
return function () {
return num;
}
} (i);
}
return result;
}
After the modified function, a self-executing anonymous function is defined, and this anonymous function assigns a value to the result array. This anonymous function passes a parameter num, which is the correct index value for the function I. The variable i is passed in when each function in the function array is called, because the function is passed by value, so the current value is copied to the parameter num. Inside this anonymous function, create a closure that returns NUM. This will return the correct index value.
Wheezing and panting. The first part is finished, now study the This object.
2. This object
The This object is bound at run time based on the execution environment of the function, in the global function, this equals window, when the function is called as a method of an object, this is equal to that object. The execution environment for anonymous functions is global, so this is pointing to window. Then in the closure to access the external scope of the active object, not directly with this, in the outer scope of the This object is stored in a closure can access variables, and then access that variable is good.
var name = ' window ';
var object = {
Name: ' Object ',
Getnamefunc:function () {
var = this;
return function () {
return that.name;
}
}
}
Console.log (Obejct.getnamefunc ());//' object '
Get busy with this, and put up the blog. = = or every time you put code to stab yourself a knife kind tired =.=
3. garbage collection mechanism, memory leaks
JS has automatic garbage collection mechanism, not manual management, but to understand the recovery mechanism, beware of memory leaks is a good habit ah.
There are two types of recycling mentioned in the Redbook, as well as marking clear and reference counting. Tag cleanup is now the most common way, and IE8 and its earlier versions also use reference counting, and here's a little bit more about the concept.
tag Cleanup : This is when variables are entered into the environment, the variables are marked as "entering the environment" and the memory used by variables entering the environment cannot be released. When a variable leaves the environment, it is marked as "out of the environment." The garbage collector marks all variables in memory when it is running, and it strips out variables in the environment where the bad guys are referenced by variables in the environment. After doing this work, there are also tagged variables that are treated as a variable to be deleted, so you can erase the memory.
reference count : keeps track of the number of times each reference type value is referenced. When declaring a variable and assigning a reference type value to it, the count is 1. The same value is assigned to another variable, and the count is added to 1. A variable that contains a reference to this value goes to another value, and the count is reduced by 1. The reference count equals 0 o'clock and can be recycled. This is a tricky question, and that's a circular reference. If a refers to b,b, reference a. The two reference count is 2 and cannot be cleared.
memory leaks : When a reference count is used by the recycle mechanism, if a circular reference occurs, some in-memory garbage cannot be reclaimed, causing a memory leak. The way to solve a circular reference is to manually break the link between the JS object and the DOM element when not in use, and dereference it. Closures also have problems with reference counting methods, such as a reference value in the outer function of the closure, which is referenced by the closure, and the reference count is at least 1 and the memory cannot be freed. As the following example.
function Assignhandler () {
var element = document.getElementById (' someelement ');
Element.onclick = function () {
Console.log (element.id);
}
}
To remove the circular reference, modify the code to:
function Assignhandler () {
var element = document.getElementById (' someelement ');
var id = element.id;
Element.onclick = function () {
Console.log (ID);
}
element = null;
}
Bar Element.id assigns a variable that can be dismissed as a circular reference. and the element = NULL to dismiss the reference to the DOM object.
4. impersonation of block-level scopes, private variables
Mimic block-level scopes
function Outputnumbers () {
for (var i = 0; I <10; i++) {
Console.log (i);
}
Console.log (i);
}
Java and other languages are block-scoped, and I in the code can be accessed within the For statement block, out of the for statement block is not accessible. JS does not have a block-level scope concept. I is defined in the active object of the function Outputnumbers function, so I can be accessed within this function. So the second print statement accesses the value of I. In addition, the JS statement will not prompt you to declare the same variable multiple times. It will only ignore the subsequent declarations. However, it performs subsequent initialization.
Closures can be used to mimic block-level scopes (private scopes).
The syntax is as follows (function () {
Block-level scopes
})();
Because any variable that is fixed in an anonymous function is destroyed at the end of execution. According to this principle, it is possible to put the code of a block of statements into a self-executing anonymous function that mimics the block-level scope.
The better use of this principle is that it is used outside the function in the global scope, restricting the addition of too many variables and functions to the global scope. Multiple developers can also work with private scopes to prevent naming conflicts. If you are communicating between multiple closures, you can define a global variable or define the appropriate method directly on this.
Private variables
Any variable defined within a function can be considered a private variable. Bar public methods that have access to private variables and functions are called privileged methods.
A closure is created inside a function, and a closure can access private variables through its own scope chain. Privileged methods have constructor methods, static private variables.
Constructor methods: Each instance will create the same method.
function MyObject () {
var privatevariable = 10;
function Privatefunc () {
return false;
}
This.publicmethod = function () {
privatevariable++;
return Privatefunc ();
}
}
Static private variables: Use the selection mode, reuse the same common function. The disadvantage is that multiple instance objects share a private variable. Shared on the, how is it private ... YY to the critical resources of the operating system ....
(function () {
var privatevariable = 10;
function Privatefunc () {
return false;
}
MyObject = function () {
};
MyObject.prototype.publicMethod = function () {
privatevariable++;
return privatevariable ();
}
})();
A summary of the JS scope, closure and related knowledge