Closures in JavaScript

Source: Internet
Author: User

Understanding mandatory Package Three basic facts

1. JS allows you to reference variables defined outside of the current function.

Ex

function Makesandwich () {

var magicingredient = "Peanut butter";

function make (filling) {

return magicingredient + ' and ' + filling;

}

return make (' jelly ');

}

Makesandwich ();

2. Even if an external function has returned, the current function can still refer to the variable defined in the external function. This means that you can return an intrinsic function.

Ex

function Mksandwich () {

var magicingredient = ' peanut butter ';

function make (filling) {

return magicingredient + ' and ' +filling;

}

return make;

}

var mk = Mksandwich ();

MK (' Jelly ');

MK (' bananas ');

MK (' marshmallows ');

JavaScript function values internally store variables that they may reference in their enclosing scope.

Functions that track variables within the scope they cover are called closures.

The Make function is a closure that references two external variables: magicingredient and filling.

A function can refer to any variable within its scope, including parameters and external function variables.

Ex

function Mksandwich (magicingredient) {

function make (filling) {

return magicingredient + ' and ' + filling;

}

return make;

}

var mk = Mksandwich (' peanut butter ');

MK (' Jelly ');

MK (' cheese ');

var mkspeical = Mksandwich (' turkey ');

Mkspeical (' Swiss ');

Mkspeical (' provolone ');

Construct a closure literal syntax-function expression

Ex

function Mksandwich (magicingredient) {

return function (filling) {

return magicingredient + ' and ' + filling;

}

}

3. The required package can update the values of the external variables. It is actually necessary to store references to external variables instead of copies of their values.

Ex

function box () {

var val = undefined;

return {

set:function (newval) {

val = newval;

},

get:function () {

return val;

},

type:function () {

return typeof Val;

},

}

}

var boxdemo = box ();

Boxdemo.type ();

Boxdemo.set (998);

Boxdemo.get ();

Boxdemo.type ();

To figure out a closure, you first need to know the scope in JavaScript.

What is the scope, you can simply understand the current context.

There are 2 types of scopes in JavaScript

belongs to the global scope.

belongs to a local scope

Global scope:

For example, we write JavaScript code on the browser side,

1

var name= ' test ';

We define a variable name directly, so the current scope of the variable is global, which is the window for the browser side.

More specifically, name is a property of the Window object.

1

2

3

Console.log (Window.name); //test

Console.log (name); //test

Console.log (this. Name); //test

The above three output methods, the result is the same, because the current scope is the Window object, this point to the current scope.

Local scope:

This type of scope is for the scope of functions in JavaScript.

Refers to a variable defined inside a function, as follows:

1

2

3

4

function Test () {

var name= ' Yijiebuyi ';

alert (this. Name);

}

The above name is a local variable, defined inside the function, so its scope is accessible within this function.

alert (this.name); This points to the current scope, because inside the function, it refers to the function scope.

If the function is outside alert (name); will be error, return undefined

But inside the function you can access the outer scope of the function, as follows:

1

2

3

4

var name= ' test ';

function Test () {

alert (name); //test

}

There is no problem with the above code, and the function's internal scope can access the global scope (or simply understand that the function internal is used to access its parent scope)

Since the function can access the parent scope variable, and the function is a class citizen, it can be used as parameter, return value, etc.

So here's the question:

1

2

3

4

5

6

function  test () {

    var  name= ' Yijiebuyi ';

    return  function () {

        console.log ( name);

    }

}

1

2

var rtn=test ();

RTN (); //yijiebuyi

We run RTN () above, get Yijiebuyi, and illustrate 2 questions:

1. The function is really a first-class citizen and can be used as a parameter when returning a value.

2. The function can access its parent scope because the Yijiebuyi is successfully exported

Let's change one more idea:

What if I don't return this anonymous function, but I want to get the value of the Name property in the test function?

It seems to be impossible to do, can only return a function to get the test function internal variables, in fact, this process is a typical closure!

We returned the anonymous function without returning var name= ' Yijiebuyi ' but ran the RTN function and got the Name property value.

So:

The function of closures is to expose private variables inside the functions. (Exposure scope)

How closures are implemented: Returns a function inside a function.

This return function automatically takes the scope of the parent function, so it can access its internal variables.

It is also because of the existence of a closure that causes the parent function to finish executing and not be garbage collected, and the variables within its scope are saved in memory for use by the closure.

Closures in JavaScript

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.