JavaScript Closure Learning Notes

Source: Internet
Author: User
Tags closure

1. Closures are functions that have access to variables in another function scope, and the common way to create closures is to create another function inside one function.

2. Under what circumstances will closures occur?

When other functions are defined inside a function, a closure is created.

3. What scenarios are needed?

If a function needs to retain a link to the parent scope after its parent function returns, a closure must be established for this purpose.

4. who's closing the bag?

When a function is created inside a function, the internal function is called externally, although the call occurs in the global domain, but the intrinsic function accesses the original domain at the time it was defined, which is its closure, and the variable to be accessed is closed.

5. What are the advantages of closures and what are the drawbacks?

Advantages of closures: You can place local variables in memory and use them for the functions you want to access, so you can avoid using global variables. The downside of closures is that closures can take up more memory than other functions, over-use closures, which can lead to excessive memory consumption and may lead to memory leaks.

6. as a local variable can be accessed by the code within the function, this and static language is no difference. The difference between closures is that local variables can still be accessed by code outside the function at the end of the function execution .

7. use of this in closures

in general, object is bound at run time based on the execution environment of the function, in the global function, this equals window, this equals that object. But, watch out! The execution environment of an anonymous function is global, so the this object pointing window. In addition, each function automatically gets two special variables when it is called: this and arguments. while the intrinsic function searches for both variables, it only searches for its active object

(1):

var name = "the window";
var object = {
Name: "My Object",
Getnamefunc:function () {
return function () {
return this.name;
};
}
};
Alert (Object.getnamefunc () ());



Object.getnamefunc () returns anonymous function functions () {return this.name after execution;} ,Object.getnamefunc () (), executes an anonymous function, at which point the execution environment is under the global scope, and its active object is the name=of the global variable"the Window", sothis.name returns to the window.

(2)

 var name =  "The window"; var object = {name :  "My object", Getnamefunc : function () {var t      hat = this;      Return function () {return that.name;    };  }  }; Alert (Object.getnamefunc ()); 

this object assigned to a named that So after you define the closure, even after the function returns, that also still quoting object object.getnamefunc () (), return " my Object ".

8. using anonymous functions, you can reduce the problem of memory consumption by closures. Any variables defined in an anonymous function will be destroyed at the end of execution.

9. Use Closures For example analysis:

( 1 )

function f () {var b = "BB"; return function () {return b;}}    var n = f (); n ();//bb

f () f () b, Continue up the scope chain lookup, find the variable b, n (), can be accessed to f ()

(2)

var n;   function f () {var b= "BBB";   n = function () {return b;   }} f (); n ();//bbb

when callingf ()function, the global variableNis assigned an intrinsic function, whenf ()after the function is called,FIs still in memory and is not destroyed because the intrinsic function is referenced by an external variable, which is indirectly equal toFWas also quoted, once, when executed intoN ()this function,N ()function first to find the current active variable in the scope chain,I can't find them .blook in the variable of the parent function up to the top level and return if found. This is also an application of closures.

(3)

function f (ARG) {var n = function () {return arg;    };    arg++;   return n;      } var m = f (123); M ();//124

when performing F (123) when the Arg Self-increment 1 , the function returns a reference to the intrinsic function assigned to the m,f () Once the function is executed, the variables inside it are not destroyed because they are referenced by the variable, so calling m (), returns a variable on the function that performs the reference (that is, the closure) Arg the value 124

( 4 )

function fn () {
var a = 0;
function f () {
Console.log (a++);
      }
return F;
     }
var b = fn ();
b (); 0
b (); 1
b (); 2

And the example above, similar. The function is bound to the scope itself, not the value currently returned by the variable or variable in the scope.

( 5 )

var result = new Array ();
function Createfunction () {
For (Var i=0;i<10;i++) {
Result[i] = function (num) {
return function () {
return num;
 };
} (i);
 }
return result;
 
 }
createfunction ();
For (Var i=0;i<result.length;i++) {
alert (Result[i] ());
 }

whencreatefunction ()at execution time, a self-executing anonymous function is defined internally, and the result of execution is returned toresult[],the same function returns this array, and when an internal anonymous function is called outside, the variable is passed inI,because the function arguments are passed by value, the variables areIthe current value is copied to thenum,inside this anonymous function, it creates and returns an accessNumclosures, soresulteach function in the array has its ownNuma copy of the variable, so you can return different values.

Summary: Just beginning to learn closure, the concept and simple examples of the analysis and summary, in the late learning through practice, continue to the concept of closure of the more profound understanding of learning.





This article is from the "dream need to adhere to" blog, please be sure to keep this source http://xiyin001.blog.51cto.com/9831864/1774942

JavaScript Closure Learning Notes

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.