Detailed Javascript function closure (straightaway

Many books on the closure is too complicated and difficult to explain, and summarize their understanding of what friends ~

Speaking before the closure, we need to understand the following concepts.

1, execution context (execution context)

 Each will create a function at the same time create an execution environment, which is the execution context. Global execution context is the global environment, an internal function of the current execution environment is the current execution context.
 Execution context defines a variable or function has access to other data, determine their own behavior.

2, execution context stack

 Execution context composed of a stack activities logically. Bottom of the stack is always a global context (globalContext), while the top is the current (active) execution context.
When a function is created and is invoked inside a function, a function of the current execution context is pushed onto the stack, if there is an internal function, continue to press the top of the stack. The bottom of the stack is always the global execution context .

3, variable object

Each execution context variable object will have associated with it, in the context of the definition of all variables and functions are on the inside. If the function, we call it the active object .
It said object is a data variable can be associated with the execution context scope (scope of data). It is a particular object associated execution contexts, for storing variables are defined in the execution context (Variables), function declarations (function declarations).

4, the scope chain

 The scope chain is used to point to an object variable, use scope is to ensure that all variables and functions have access to the execution environment of orderly access. Forefront of scope, the object is always variable environment where the code currently executing .
 Child objects will look for an upward all the variables of a parent object to. So, all variables parent object, child objects are visible, not vice versa.

var f1 = function() {
    function f2() {
        function f3() {}
    }
}
//f3中 作用域链就是 f3活动对象 -> f2活动对象 -> f1活动对象 -> global活动对象

You can begin to talk about closure

Definition: the closure is a function of another function has access to scope variables .
Is not it a bit too abstract? for example

var outter = function() {
    var a = 1;
    function inner() {
        return a;
    }
    return inner; //返回里面这个函数
}
var result = outter(); //外部得到了返回的里面那个函数
console.log(result()); //1

JavaScript is apparent from the characteristics of the scope chain, in which the function of external variables can be accessed, but the reverse is not acceptable. But above example did, this is closure.
Since the inner outter local variables can be read in, so long as the inner as the return value, we can not read its internal variables outside the outter yet!
On an inner code function, that is closures.
"Closure" on a variety of professional literature (closure) definition is very abstract, difficult to understand. My understanding is that the closure is a function of internal variables can be read by other functions.
Since the Javascript language, only the internal function subroutine to read local variables, the closure can be simply interpreted as "a defined function within the function" .
Therefore, in essence, the closure is a function of the internal and external bridge connecting function .

Use some of the problems often occur closures

1, the closure can get last value contained in the function of any variable

It seems a bit abstract. Do not forget, closures saved the entire variable object, rather than a particular variable . In fact, here you can think of it as similar to a reference.

function createArray() {
    var result = new Array();

    for(var i = 0;i<10;i++) {
        result[i] = function() {
            return i;
        };
    }
    return result;
}
var r = createArray();
console.log(r);
for(var i=0;i<10;++i)
    console.log(r[i]()); //10个10

The reason is that the entire closure is saved variable object, so that each function are stored as the variable object . They refer to are i the same variable . Therefore, execution time of closing the package, has been performed to 10 i, it is naturally returned 10 i.

2, on this subject

We know that, the this object is runtime function-based execution environment binding : global functions, this equal to the window, and when the function is invoked as an object method, this is equal to that object .
However, the execution environment of the anonymous function is global, so it usually points to this target window

var name = "The Window";
var object = {
    name: "My object",
    getNameFunc: function() {
        return function() {
            return this.name;
        };
    }
}
console.log(object.getNameFunc()()); //The Window

Why the final result is "The Window" instead of object inside the name "My object" it?
 First, we must understand the function of a function as function calls and method calls.
 We put the last sentence is split into two steps:

var first = object.getNameFunc();
var second = first

among them

  • The first step, anonymous function to return the first obtained at this time getNameFunc () as a method of object invocation , if getNameFunc () this is used, this refers to the case of the Object object.
  • The second step, first calling the function, can be clearly found that this time first function call, first function is not invoked in the object, and therefore as a function call , in the global scope, and therefore the first function of this point It is a window.
    Why not get this anonymous function that contains the object scope (outside the scope) it?
     As each function is called, its active object will automatically get two special variables: this and arguments. Internal search function in two variables, it will only search for active objects so far, and therefore can never directly access external functions of two variables.


    So, how to get the role of external variables in this it?
    The scope of this external objects stored in a variable closure can gain access to the inside, you can let the closure of access to the object.
var name = "The Window";
var object = {
    name: "My object",
    getNameFunc: function() {
        var name = 19;
        var that = this;
        return function() {
            return that.name;
        };
    }
}
console.log(object.getNameFunc()()); //My object

At this point calls, activity variables during execution getNameFunc What? name that function. In the implementation of the anonymous function, while references getNameFunc active object () in, so you can get the value and age of that. However, due to the anonymous function is invoked in the global environment, and therefore anonymous inner function this point or window .

Closure use summary

1, can be read variables inside a function, a function to establish internal and external bridge;
2, let the value of some variables remain in memory.

Precautions closures are used

1) Due to the closure will make the function of the variables are stored in memory, memory consumption is large, it can not be abused closure, otherwise it will cause performance problems webpage in IE may lead to memory leaks. The solution is, before exiting the function will delete all local variables are not used.
2) Closure will function outside the parent, the parent function changes the value of the internal variable. So, if you take the parent function as an object (object) to use, the closure of its public methods (Public Method) as, the internal variable as its private property (private value), then you must be careful not to just change the value of the parent function of internal variables.

"JavaScript Advanced Programming 3rd Edition"

Guess you like

Origin www.cnblogs.com/TRY0929/p/11876803.html