JavaScript function closure (closure)

Source: Internet
Author: User
Tags closure object object

First, feel the closure of the JavaScript function

Two, closed package

1, definition: A closure is a function that can read the internal variables of other functions, because in the JavaScript language, only the child functions inside the function can read the local variables, so the closure can be simply understood as: a function defined within a function, in short, Closures act as bridges that connect functions inside and outside functions

2, Function: 1, you can read the variables inside the function, 2, you can keep the values of these variables are always stored in memory

3, note the point: 1, first because the closure will make the variables in the function are stored in memory, memory consumption is very large, so we can not abuse closures, otherwise it will affect the performance of the Web page. There may be a memory leak in IE browser. The workaround is to remove all unused local variables before exiting the function

2, the closure changes the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, take the closure as its public method and take the internal variable as its private property. Be careful not to change the values of the internal variables of the parent function.

Three: Practice

var name = "the window";

var object = {
Name: "My Object",

Getnamefunc:function () {
return function () {

return this.name;

};

}

};

Alert (Object.getnamefunc () ());

"The Window" pops up because this point is pointing to the browser window object

var name = "the window";

var object = {
Name: "My Object",

Getnamefunc:function () {
var = this;
return function () {

return that.name;
};

}

};

Alert (Object.getnamefunc () ());

The "My Object" pops up because this point is pointing to the current object object

JavaScript function closure (closure)

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.