JS Closed Package

Source: Internet
Author: User
Tags variable scope

JS Closed Package

Write before the closure:

context is the smallest set of data required for a program to run. We can understand the context from context switch, in a multi-process or multi-threaded environment, the task switch first interrupts the current task, the computing resources to the next task. Because the previous task will be restored later, the time to save the scene, that is, the context of the current task, can also be called the environment. That is, the context is the smallest set of data needed to recover the site. One thing that's easy to stun is that the context, the environment, which we're talking about here, is sometimes called scope, which is sometimes a mix of two concepts. However, they have different priorities, which are explained in the next section.

In addition, the common scenario in JavaScript is the execution of a method/function. From the point of view of a program, all the variables required for this program to run are the context.

Scope (Scope) is the scope of visibility of identifiers (variables) within a program. A scope rule is to maintain the visibility of identifiers according to specific rules to determine the access rights of the currently executing code to those identifiers. Scope (scope) is determined under a specific scope rule.

As mentioned earlier, sometimes context, environment, scope is synonymous; However, context refers to the overall environment, where the scope is concerned with the accessibility (visibility) of identifiers (variables). The context determines that the scope is determined according to the scope rules of the specific programming language. This is the context and scope of the relationship.

When writing JavaScript code, if function is a parameter, you can specify that it is called on a specific object, which is often called the context

1, the concept of closures

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

A closure is a combination of a function and a lexical environment that declares the function. From a theoretical standpoint, all functions are closures.
To understand closures, you must first understand the special variable scope of JavaScript.

2, closure example

Example one:

function makeFunc() {    let name = "Mozilla";    function displayName() {        console.log(`name = ${name}`);     }    return displayName;}let myFunc = makeFunc();myFunc();

This code looks awkward but works fine. In some programming languages, local variables in functions are only available during the execution of a function. Once Makefunc () is executed, it is reasonable to assume that the name variable will no longer be available. However, because the code is working fine, it is clearly not the case in JavaScript.

The answer to this puzzle is that myFunc becomes a closed bag. Closures are a special kind of object. It consists of two parts: a function, and the environment in which the function is created. An environment consists of any local variables that are in scope when the closure is created. In our example, Myfuunc is a closure, formed by the "Mozilla" string that exists when the DisplayName function and the closure are created.

Example:

function makeAdder(x) {  return function(y) {    return x + y;  };}var add5 = makeAdder(5);var add10 = makeAdder(10);console.log(add5(2));  // 7console.log(add10(2)); // 12

In this example, we define the Makeadder (x) function: With a parameter x and return a new function. The returned function has a parameter Y, and returns the and of X and Y.

Essentially, Makeadder is a function factory-creating a function that sums the specified value with its arguments, in the example above, we created two new functions using a function factory-one that sums its arguments and 5, the other and 10.

Add5 and ADD10 are closures. They share the same function definitions, but save different environments. In the ADD5 environment, X is 5. In Add10, X is 10.

3, closure of the application scenario

One

Closures allow the function to be connected to some of the data (environment) it is manipulating. This is obviously similar to object-oriented programming. In object-oriented programming, objects allow us to associate certain data (properties of an object) with one or more methods.

Thus, in general, you can use closures in places where you can use objects with only one method.

Most of the time we write JavaScript code is event-driven to define a behavior, and then add it to the event that the user triggers (such as tapping or pressing). Our code is also usually added as a callback: a function that executes in response to an event.

For example, we want to add a button on the page to adjust the font size. One is to specify the font-size of the body element in pixels, and then set other elements in the page (such as the font size of the header) by relative EM units. Use JS to write the time. We can modify the Font-size property of the body:

function makeSizer(size) {  return function() {    document.body.style.fontSize = size + ‘px‘;  };}var size12 = makeSizer(12);var size14 = makeSizer(14);var size16 = makeSizer(16);

Both:
Simulating private methods with closures

Three:

for (var i = 0; i < 5; i++) {    setTimeout(function() {        console.log(‘i: ‘,i);    }, 1000);} console.log(i); //输出5i:  5i:  5i:  5i:  5i:  5

1, the For loop and the console outside the loop body are synchronous, so the for loop is executed before the external console.log is executed. (Sync first)

2, for the loop inside there is a settimeout callback, he is the bottom of the existence, only the last execution. (Callback bottom)

So, why did we first output 5?

It is very well understood that the For loop executes first, but does not give the settimeout a parameter (the callback is the bottom), and when the For loop executes, the settimeout is passed, and the external console prints 5 because the For loop executes.

The simplest solution is to let modify.

Can see here net red front face question

4, the use of the meaning of closures

Local variables cannot be shared and persisted, and global variables can cause variable contamination, so we want a mechanism that can persist variables for long periods without causing global pollution.

5, the interview about closures
function fun(n,o) {  console.log(o)  return {    fun:function(m){      return fun(m,n);    }  };}var a = fun(0);  a.fun(1);  a.fun(2);  a.fun(3);//undefined,?,?,?var b = fun(0).fun(1).fun(2).fun(3);//undefined,?,?,?var c = fun(0).fun(1);  c.fun(2);  c.fun(3);//undefined,?,?,?//问:三行a,b,c的输出分别是什么?
//第一行avar a = fun(0);  a.fun(1);  a.fun(2);  a.fun(3);

It can be learned that the first fun (0) is called in the first layer fun function. The second fun (1) is a fun function that calls the return value of the previous fun, so:

After the first few fun (1), Fun (2), Fun (3), the function is called the second layer fun function.

Hence

When the first call to Fun (0), O is undefined;

The second call Fun (1) when M is 1, at this time fun closed the outer function of N, that is, the first call of the n=0, that is, m=1,n=0, and in the internal call the first layer fun function fun (1,0); so o is 0;

The third call to Fun (2) when M is 2, but still call A.fun, so still closed the first call when the N, so the internal call the first layer of fun (2,0); so o is 0

Fourth time similarly;

That is, the final answer is undefined,0,0,0.

//第二行bvar b = fun(0).fun(1).fun(2).fun(3);//undefined,?,?,?

First from the fun (0), it must be the first fun function of the call, and his return value is an object, so the second fun (1) Call is the second layer of fun function, the next few are called the second layer of fun function.

Hence

In the first call to the first layer fun (0), O is undefined;

The second call. Fun (1) when M is 1, at this time fun closed the outer function of N, that is, the first call of the n=0, that is, m=1,n=0, and in the internal call the first layer fun function fun (1,0), so O is 0;

The third call. Fun (2) when M is 2, the current fun function is not the first time the returned object executes, but the second execution of the return object. And in the second execution of the first layer of fun function time (1,0) so n=1,o=0, return closed the second time of N, so in the third call to the third layer fun function m=2,n=1, that is, call the first layer fun function fun (2,1), so O is 1;

Fourth call. Fun (3) m is 3, closed the third call of N, the same, the final call to the first layer fun function is fun (3,2); so o is 2;

That's the final answer: undefined,0,1,2

//第三行cvar c = fun(0).fun(1);  c.fun(2);  c.fun(3);//undefined,?,?,?

According to the previous two examples, it is possible to know:

Fun (0) for the implementation of the first layer of fun function,. Fun (1) is a fun (0) Return of the second layer of the fun function, where the statement ends, then C is a fun (1) of the return value, rather than fun (0) return value, so C is also a fun (1) second execution of n value. C.fun (2) is a fun (1) Return of the second layer of fun function, C.fun (3) is also a fun (1) Return of the second layer of fun function.

Hence

In the first call to the first layer fun (0), O is undefined;

The second call. Fun (1) when M is 1, at this time fun closed the outer function of N, that is, the first call of the n=0, that is, m=1,n=0, and in the internal call the first layer fun function fun (1,0), so O is 0;

The third call. Fun (2) when M is 2, at this time the fun closure is the second call of the N=1, that is, m=2,n=1, and in the internal call the first layer fun function fun (2,1); so o is 1;

The fourth time. Fun (3) is the same, but still the second return value of the call, and finally call the first layer fun function fun (3,1), so O is also 1

That's the final answer: undefined,0,1,1

6, two small topics
var name = "The Window";  var object = {    name : "My Object",    getNameFunc : function(){      return function(){        return this.name;      };    }  };  alert(object.getNameFunc()());
var name = "The Window";  var object = {    name : "My Object",    getNameFunc : function(){      var that = this;      return function(){        return that.name;      };    }  };  alert(object.getNameFunc()());

JS Closed Package

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.