The parsing of the anonymous function of JavaScript __ block chain

Source: Internet
Author: User
Tags closure

Anonymous functions are effective in ensuring that JavaScript is written on the page without causing global variables to be contaminated.


An example of an anonymous function running automatically:

1. (function () {alert (1);}) ();(Common)

2. (function () {alert (2);} ());

3.void function () {alert (3);} ();


The role of ():

Parentheses can divide our expression into chunks, and each piece, that is, each pair of parentheses, has a return value. This return value is actually the return value of an expression in parentheses. So, when we enclose the anonymous function with a pair of parentheses, the parentheses are actually returned, which is the function object for the anonymous functions. Therefore, the parentheses and the anonymous function are the names of the functions we have to get its reference position. So if you add the argument list after this reference variable, you implement the calling form of the normal function.


Example of an anonymous function call running:

var abc=function (x,y) {return x+y;} alert (ABC (2,3));


Closed Bag
What the closures are. A closure is a code block in a program language that allows a class of functions to exist and the free variables defined in a first-level function are not released until the first-level function is released, and the free variables can be applied outside the first-level function. (recursive)


Closure Example:

var abc=function (y) {
var x=y;//this is a local variable
return function () {
Alert (x + +), or this is where the x of the first-level function local variable in the closure attribute is invoked and manipulated
alert (y--);//referenced parameter variable is also a free variable
}} (5);//Initialize
ABC ();//"5" "5"
ABC ();//"6" "4"
ABC ();//"7" "3"

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.