JS in the closure (accumulation summary)

Source: Internet
Author: User

What is a closure package :

when an intrinsic function in the scope that defines it the external when referenced , the inner function's closure is created , and if the intrinsic function references a variable that is located outside the function, when the external function call is complete , the These variables are not freed in memory because the closures require them .

Example 1

function Outerfun ()


var a=0;

function Innerfun ()



alert (a);


return innerfun; Watch this .


var obj=outerfun ();

obj (); result is 1

obj (); result is 2

var obj2=outerfun ();

Obj2 (); result is 1

Obj2 (); result is 2

Example 2

function Foo () {

var i = 0;

return function () {

Console.log (i++);



var f1 = Foo (),

F2 = Foo ();

F1 ();

F1 ();

F2 ();

0 1 0

since the In the Javascript language, only sub-functions inside the function can read local variables, so the closure can be simply understood as " a function defined inside a function ".

The maximum use of closures is two, one is the ability to read variables inside the function, and the other is to keep these variables in memory, that is, the closure can make it the birth of the environment has always existed. Take a look at the following example, the closure allows internal variables to remember the result of the last call.

So memory consumption is very large. Therefore cannot abuse the closure, otherwise may cause the webpage the performance question.

JS in the closure (accumulation summary)

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.