About Javascript anonymous Functions

Source: Internet
Author: User
When an anonymous function is enclosed in parentheses, the anonymous function can run immediately.

JQuery has the following code:

(function(){ // code here})();

When an anonymous function is enclosed and a bracket is added to it, the function can run immediately. What a magic!

To say anonymous functions, we should first start with the functions themselves. The function is defined as follows: a function is a rule that assigns a unique output value to each input ".

Of course, this is just a mathematical definition. However, in computer programming languages, the definition of functions is also far from 10. As we all know, functions in computers are similar to descriptions in mathematical definitions. They process a number of input data after the logic operations set by the Code, returns a unique set of code combination blocks. -- Of course, the exception is that the input data is null, the output data is null, or both are empty.

Next, let's take a preliminary look at concepts related to anonymous functions.

Function declaration (function Statement)

To use a function, we must first declare its existence. The most common method is to use a function statement to define a function, such:

function abc(){   // code to process }

Of course, functions can also contain parameters or even return values.

function abc(x,y){   return x+y; }

However, no matter how you define your Function, the JS interpreter translates it into a Function object. For example, if you define the function number of one of the above examples, enter the following code:

alert(typeof abc);// "function"

Your browser will pop up a prompt box prompting you that abc is a Function object. So what is a Function object?

Function object

Function objects are inherent objects in JavaScript. All functions are actually Function objects. Let's first look at whether the Function object can directly use the constructor to create a new Function? The answer is yes. For example:

var abc = new Function("x","y","return x*y;"); alert(abc(2,3)); // "6"

I believe you have some knowledge about how to declare a function. So what is an anonymous function?

What is an anonymous function?

As the name implies, an anonymous function is a function without a real name. For example, we can remove the name of the function in the above example and determine whether it is a function:

alert(typeof function(){});// "function" alert(typeof function(x,y){return x+y;});// "function" alert(typeof new Function("x","y","return x*y;"))// "function"

We can easily see that they are all Function objects. In other words, they are all functions, but they all have a feature-No Name. So we call them "anonymous functions ". However, we cannot find them because they do not have a "name. This raises the question of how to call an anonymous function.

There are three methods to define a function in Javascript:

  • Function keyword statement:
  • function fnMethodName(x){alert(x);}
  • Function Literals ):
  • var fnMethodName = function(x){alert(x);}
  • Function () constructor:
  • var fnMethodName = new Function('x','alert(x);')
Call of anonymous Functions

To call a function, we must have a method to locate it and reference it. Therefore, we need to find a name for it. For example:

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

The above operation is actually equivalent to defining a function in another way. This usage is frequently encountered. For example, when we set a DOM element event processing function, we usually do not set their names, but assign the corresponding event to reference an anonymous function.

There is also another way to call an anonymous function, that is, the jQuery snippet we see -- use () to enclose an anonymous function, and then add a pair of parentheses (including the parameter list ). Let's take a look at the following example:

alert((function(x,y){return x+y;})(2,3));// "5" alert((new Function("x","y","return x*y;"))(2,3));// "6"

Many may wonder why this method can be called successfully? If this application is strange, let's take a look at the following explanation.

Do you know the role of parentheses? Parentheses can combine our expressions into blocks, and each block, that is, each pair of parentheses, has a return value. The returned value is actually the return value of the expression in parentheses. Therefore, when we enclose anonymous functions with a pair of parentheses, in fact, parentheses return the Function object of an anonymous Function. Therefore, adding an anonymous function to the parentheses is like a function with a name, and we get its reference position. Therefore, if the parameter list is added after the referenced variable, the call form of the common function is implemented.

I don't know if you can understand the above text. If you still can't understand it, let's try the following code again.

// Assign the anonymous function object to abcvar abc = function (x, y) {return x + y ;}; // The constructor of abc is the same as the constructor of the anonymous function. That is to say, the implementation of the two functions is the same. Alert (abc). constructor = (function (x, y) {return x + y;}). constructor );

PS: constructor refers to the function for creating objects. That is, the function body represented by the function object.

In short, it is understood as the function object returned by the parentheses expression (the anonymous function included in the parentheses), and then the function object can be called as a normal parameter list. (The preceding error is reported. Only function expressions cannot directly call functions. To remove Anonymous function brackets, you must assign values to the expressions. That is, (function () {alert (1)}) () should be equivalent to a = function () {alert (1, cannot even remove a = .)

About closures

What is a closure? A closure refers to a code block in a programming language that allows a level-1 function to exist and the free variables defined in the level-1 function cannot be released until the level-1 function is released, these unreleased free variables can also be applied to a level-1 function.

How? See a sweat ...... It's okay, so do I (although I understand it, it's just a matter of expression ability ). Let's change to a simpler method: closure is actually a language feature. It refers to a programming language that allows functions to be viewed as objects, then, you can define instance (local) variables in functions like operations in objects. These variables can be saved to the function until the Instance Object of the function is destroyed, other code blocks can get the value of these instance (local) variables in some way and perform application extension.

I don't know whether it will be clearer after this explanation. If I still don't understand it, Let's simplify it: closure, actually, it refers to the local variables defined in the function that can be called by the code in the program language.

Now let's look at an example:

Var abc = function (y) {var x = y; // This is the local variable return function () {// x that calls the local variable of the first-level function in the closure feature, perform the alert (x ++); alert (y --); // The referenced parameter variable is also a free variable} (5); // initialize abc (); // "5" "5" abc (); // "6" "4" abc (); // "7" "3" alert (x ); // error! "X" is not defined!

Can you determine whether the code snippet of jQuery is closed?

Let me understand it. Whether the closure feature is applied, you must determine whether the Code contains the most important elements: local variables not destroyed. Obviously, the closure feature cannot be applied without any implemented anonymous functions. But what if an anonymous function is implemented? You have to determine whether the local variables that are not destroyed are used in its implementation. So if you ask what features of JS are applied to the jQuery code snippet in the beginning? Then it is just a call of anonymous and anonymous functions. However, it implies the closure feature and can implement the closure application at any time. Because JS is born with this feature.

Differences between Function literal and Function () constructor

Although a Function is an anonymous Function, the syntax allows you to specify any Function name for the Function. When writing a recursive Function, you can call it yourself. If you use Function () to construct a Function, you cannot.

var f = function fact(x) { if (x < = 1) return 1; else return x*fact(x-1); };

Function () constructor allows dynamic creation and compilation of Javascript code during runtime. In this way, it is similar to the global function eval ().

Function () constructor parses the Function body each time it is executed and creates a new Function object. Therefore, it is very inefficient to call Function () constructor in a loop or frequently executed Function. On the contrary, function literal is not re-compiled every time.

When using Function () to construct a Function, it does not follow the typical scope. It always treats it as a top-level Function for execution.

Var y = "global"; function constructFunction () {var y = "local"; return new Function ("return y "); // unable to obtain local variable} alert (constructFunction (); // output "global"

Compared with Function keyword definition, the Function () constructor has many features and is difficult to use. Therefore, this technology is rarely used. The function literal expression is very similar to the function keyword definition. Considering the difference above, although there are bugs in some webkit engines under OS X 10.4.3 for anonymous functions with literally sent messages, however, the anonymous functions we usually call all refer to anonymous functions in the form of functions literally. For more details, see The Functions chapter in JavaScript: The Definitive Guide, 5th Edition.

Code mode of anonymous Functions

If an anonymous function is written like this, an error is returned:

// The browser reports a syntax error. Function () {alert (1 );}();

However, if you add the = sign above, you will be right:

var sum = function() {return 1;}();

First, the function () {...} enclosed by parentheses is considered as a function expression by the js engine, and the later () calls this anonymous function.

If you write function (){...} () that is a syntax error, because the js engine will expect a function declaration with a name (the func declaration is different from the func expression );

However, it can be written as void function (){...} () is also possible, because the void keyword will tell the js engine to follow an expression, so it will be recognized as an anonymous function object generated by a function expression, and call the results. void will discard the call results.

  1. Function literal: first declare a function object and then execute it.
  2. (function(){ alert(1); }) ();
  3. Priority expression: Because the JavaScript Execution expression is from inside the parentheses to the outside, you can use parentheses to forcibly execute the declared function.
  4. ( function(){ alert(2); } () );
  5. Void Operator: Use the void operator to execute a separate operand without parentheses.
  6. void function(){ alert(3); }() 

These three methods are equivalent. For personal reasons, 3rd are preferred, and 1st are seen and used in actual applications.

Application of anonymous Functions

The first sentence in Javascript's module mode is "global variables are the Devil ". With the var keyword, the anonymous function can effectively ensure that Javascript is written on the page without causing global variable pollution. This is very effective and elegant when adding Javascript to a page that is not very familiar. In fact, YUI and its corresponding examples use a lot of anonymous functions, and many other Javascript libraries also use them.

The cornerstone of functional programming in Javascript. For details, see compiling beautiful JavaScript with functional programming technology and functional JavaScript programming guide.

Address of this article: http://www.nowamagic.net/librarys/veda/detail/203,welcome.

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.