Closures and anonymous functions in JavaScript

Source: Internet
Author: User
Tags closure variable scope

Knowledge Content:

1. Preliminary Knowledge-function expressions

2. Anonymous functions

3. Closures

First, the function expression

1. Two ways to define functions

function declaration:

1 function func (arg0, arg1, arg2) {2     //Functional Body  3}

function expression:

1 var func = function (arg0, arg1, arg2) {2     //function body  3}

2. Precautions

function expressions must be assigned before they are used! The code like the following is wrong:

1 Say () 2 var say = function () {3     console.log ("123") 4}

A function expression can be assigned as a normal variable in a branch based on a condition:

1//The following code assigns different function expressions according to different condition Sayhi 2 var sayhi 3 var condition = True  //hi! 4//var condition = false  // Hello! 5  6 if (condition) {7     sayhi = function () {8         console.log ("hi!") 9     }10}11 else{12     sayhi = function () {          console.log ("hello!")     }15}16 Sayhi ()

The above code has different operating effects:

Can create a function to assign to a variable, of course, you can also return the function as the return value of other functions

Second, anonymous function

1. What is an anonymous function

Anonymous functions: The usual use of anonymous functions is performed immediately. This is often called self-executing anonymous functions or self-invoking anonymous functions. Commonly used to build sandbox mode, the role is to open up a closed variable scope environment, in the multi-person joint work, the combination of JS code, the same variable will not be conflicting with each other problem

2. Detailed notation of anonymous functions

The following two types of anonymous functions are used, the first is recommended:

1 (function () {2   console.log ("I am anonymous mode 1"); 3});  I'm anonymous. 5 (function () {6   console.log ("I am anonymous mode 2"); 7} ());  I'm anonymous. 9 Console.log ((function () {}). name);  Name is empty

Note: in fact, an anonymous function that executes immediately is not a function , because it has been executed, so it is a result that is a reference to the result of the current anonymous function execution (the function executes the default return undefined). The result can be a string, a number, or a null/false/true, an object, an array, or a function (both objects and arrays can contain functions), and when the returned result contains a function, the result of this immediately executing anonymous function is the typical closure.

Three, closed package

1. What is closures

What is closures: closures refer to functions that have access to variables in another function scope, and the official explanation for closures is that an expression (usually a function) that has many variables and environments that bind those variables is also part of the expression

    • As a reference to a function variable, when the function returns, it is in the active state
    • A closure is when a function returns, a stack that does not release resources

Simply put, JavaScript allows the use of intrinsic functions---that is, function definitions and function expressions in the function body of another function. And these intrinsics can access all the local variables, arguments, and other intrinsics declared in the outer function in which they are located. When one of these intrinsic functions is called outside the outer function that contains them, a closure is formed

2. How closures are written

12345678910 functiona(){  var n = 0;  functioninc() {    n++;    console.log(n);  }  inc();   inc(); }a(); //控制台输出1,再输出2

It's simple. Take another look at the code:

12345678910 functiona(){  varn = 0;  this.inc = function() {    n++;     console.log(n);  };}varc = newa();c.inc();  //控制台输出1c.inc();  //控制台输出2

It's simple.

What is a closure package? This is the closure!

A function that has access to a variable within the scope of another function is a closure. Here the INC function accesses the variable n in constructor A, thus forming a closure.

Take another look at the code:

1234567891011 functiona(){  var n = 0;  functioninc(){    n++;     console.log(n);  }  returninc;}varc = a();c();  //控制台输出1c();  //控制台输出2

See how it's done:

var c = couter (), this sentence couter () returns the function Inc, which is equivalent to var c = Inc;

C (), this sentence is equivalent to Inc (); Note that the function name is just an identifier (a pointer to a function) and () is the execution function.

The following three sentences are translated: var c = Inc;  Inc (); Inc (), is it different from the first piece of code? No

The reason for this writing:
We know that every function of JS is a small black house, it can get outside information, but the outside world can't directly see the content. Put the variable n into the small black room, in addition to the INC function, there is no other way to touch the variable n, and in the function a outside the definition of the same name variable n is not affected, this is called enhanced "encapsulation."

And the reason to return function ID Inc with Return is because the INC function cannot be called directly outside the A function, so return Inc is associated with the outside, and this in Code 2 also links Inc to the outside.

3. The role of closures

    • Implementing an anonymous self-executing function
    • Implementing encapsulation
    • Implementing Classes and Inheritance

(1) Closure implementation anonymous self-executing function see the following anonymous function in detail

(2) Closure implementation Package

There is no concept of private members in JavaScript, all object properties are public, but there is a concept of a private variable. Simply put, any variable defined in a function can be considered a private variable, because these variables cannot be accessed outside of the function

Private variables include:

    • Parameters of the function
    • Local variables of the function
    • Other functions defined inside the function

In addition, using the closure principle, we can create public methods for accessing private variables: Create a closure within a function, the closure of which accesses these variables through the scope chain, so that the external cannot directly access internal variables can only be accessed through certain methods, thus enabling encapsulation

1 varperson =function(){    2     // variable scope is inside function, external unreachable3     varName = "Default"; 4        5     return {    6GetName:function(){    7            returnname; 8        },    9SetName:function(newName) {TenName =NewName;  One        }     A     }     - }();  -       thePrint (person.name);// direct access with a result of undefined - print (Person.getname ());  -Person.setname ("wyb");  - print (Person.getname ());  +    

(3) Closure implementation class and inheritance

1 functionPerson () {2     varName = "Default"; 3        4     return {    5GetName:function(){    6            returnname; 7        },    8SetName:function(newName) {9Name =NewName; Ten        }     One     }     A     };  -  -     varp =NewPerson (); theP.setname ("Tom"); - alert (P.getname ()); -  -     vars=function(){}; +     //inherit from person -S.prototype =NewPerson (); +     //Adding Private methods AS.prototype.say =function(){ atAlert ("Hello,my name is S"); -     }; -     varj =News (); -J.setname ("s"); - J.say (); -Alert (J.getname ());

4. Closure considerations

(1) Closures and variables

Closures can only get the last value of any variable in the containing function, and the closure holds the entire variable object, not a particular variable

1 function Createfunctions () {2     var result = new Array () 3  4 for     (var i=0; i < i++) {5         result[i] = function () {6             return i; 7         } 8     } 9     return result11} n    var foo = createfunction ()

The result is not as expected in Foo, but in 10, which is why? Simply declaring a function, the engine does not find or assign any variables inside the function. Only syntax errors inside the function are checked (if an illegal statement is added to the inner function, the error is not called), that is, before the result is returned

Result is not executed, and all I references in the anonymous function after it is returned are the same variable (the last value 10), so the value of I within each function is 10

See this article for detailed instructions: https://www.cnblogs.com/kindofblue/p/4907847.html

Forcing the behavior of a closure to match expectations by creating another anonymous function:

1 function Createfunctions () {2     var result = new Array () 3  4 for     (var i=0; i < i++) {5         result[i] = function (num) {6             return function () {7                  return num 8             } 9         } (i)     }11     return result13}  

(2) The This object in the closure

About this object:

    • The This object is a function-based execution environment binding at run time.
    • In the global function this is equivalent to window, when the function is called as a method of an object this is equivalent to that object
    • The use of this object in closures may cause some problems
1 var name = "the window"; 2 var object = {3     name: "My Object", 4     getnamefunc:function () {5         return function () {6             return this. Name 7         }; 8     } 9}10 alert (Object.getnamefunc ()); "The Window"

Why did the final result be "the window" instead of the name "My object" inside the object?

First, to understand the function as a function call and function as a method call, we split the last sentence into two steps to execute:

var first = Object.getnamefunc (); var second = first ();

In the first step, we get the anonymous function returned by Getnamefunc () as the method call of object, and if this is used in Getnamefunc (), this point is to object.

In the second step, the first function is called, it is very clear that the first function is called, and the first function is not called in the object, so it is called by the global scope, so the this in the first function points to the window .

And look at the following sentence:

Why does the anonymous function not get the This object that contains the scope (outer scope)?

When each function is called, its active object will automatically get two special variables: this and arguments.  When the intrinsic function searches for these two variables, it only searches for its active object, so it is never possible to directly access these two variables in the external function. JavaScript Advanced Programming

So, how do you get this in the outer scope? You can save this in an external scope in a variable that the closure can access. As follows:

1 var name = "the window"; 2 var object = {3     name: "My Object", 4     getnamefunc:function () {5         var = this;   Save this Getnamefunc () in that variable 6         var age = 7         return function () {8             return that.name; 9         };10     }11 }12 alert (Object.getnamefunc ());   "My Object"

(3) Mimic block-level scopes

There is no block-level scope in JavaScript, JavaScript never tells you whether to declare the same variable more than once, and in this case it will only turn a blind eye to subsequent declarations, but we can use anonymous functions and closures to implement block-level scopes

The anonymous functions used as block-level scopes are as follows:

1 (function () {2    //This is block-level scope   3});

The above anonymous function is also equivalent to this form:

1 var someFunction = function () {2     //This is a block level scope  3}4 someFunction ()

Considerations for anonymous functions and impersonation block-level scopes:

    • Any variables defined in the anonymous function will be destroyed at the end of execution
    • A variable in the private scope (anonymous function) that can access the outer function is because the anonymous function is a closure that accesses all the variables in the containing scope

For the above two points, the sample code is as follows:

1 function func (count) {2     (function () {3 for         (var i=0; i < count; i++) {4             console.log (i)      5         }6     }) ();  7     8     console.log (i)  //Cause an error!   9}

Closures and anonymous functions in JavaScript

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.