My view on the JavaScript closure mechanism

Source: Internet
Author: User
Tags closure

My understanding: JavaScript functions work in the scope that it defines, not the scopes it executes, and the variables defined within the scope that it defines are global variables relative to this function,

This is the so-called "closure."


Look at an example: (Can you think of what the output is?) )

The <script>
function setupsomeglobals () {
	var num = 666;
	Galertnumber = function () {
		alert (num);
	};
	Gincreasenumber = function () {
		alert (num++);
	}
	Gsetnumber = function (x) {
		num = x;
	}
}
var num = 1;
Setupsomeglobals ();
Galertnumber (); 666
Gincreasenumber ();//666
galertnumber ();//667
Gsetnumber (a)
; Galertnumber ()//12
</script>

Here are 3 functions declared within the function setupsomeglobals () function: Galertnumber (), Gincreasenumber (), Gsetnumber (x), and a variable num declared inside the function setupsomeglobals () function. So, 3 internal functions Galertnumber (), Gincreasenumber (), Gsetnumber (x) should work in their "definition" Scope--function setupsomeglobals () Internally, and, correspondingly, the NUM variable is a global variable for these 3 internal functions in the setupsomeglobals () scope.

In this way, it is not difficult to understand the above output.


But, wait ... There are no problems found.

Num, as a local variable, is not destroyed after the closure is formed, which results in a memory leak. So be careful to use closures oh.


Reference: http://coolshell.cn/articles/6731.html


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.