Analysis of Javascript anonymous and self-executed functions, analysis of javascript

Source: Internet
Author: User

Analysis of Javascript anonymous and self-executed functions, analysis of javascript

Functions are the most flexible objects in JavaScript. Here we will only explain the usage of anonymous functions. Anonymous function: A function without a function name.

Function definition can be roughly divided into three methods:

First: this is also the most common one.

function double(x){ return 2 * x; }

Second: This method uses the Function constructor and uses the parameter list and Function bodies as strings. This method is inconvenient and is not recommended.

var double = new Function('x', 'return 2 * x;');

Third:

var double = function(x) { return 2* x; }

Note that the function on the right of "=" is an anonymous function. After the function is created, the function is assigned to the variable square.

Create an anonymous Function

The first method is to define the square function, which is also one of the most common methods.

Method 2:

(function(x, y){ alert(x + y); })(2, 3);

An anonymous function (in the first bracket) is created here, and the second bracket is used to call the anonymous function and input parameters. Parentheses are expressions, and expressions have returned values. Therefore, you can add a pair of parentheses to execute them.

Self-executed anonymous Functions

1. What are self-executed anonymous functions?

It refers to a function like this: (function {// code })();

2. Questions

Why (function {// code}) (); can be executed, but function {// code} (); returns an error?

3. Analysis

(1) first, we need to know the differences between the two:
(Function {// code}) is an expression, and function {// code} is a function declaration.
(2). Second, features of js "pre-compilation:
In the "pre-compilation" phase, js will explain the function declaration, but will ignore the table type.
(3 ). when js executes function () {// code} ();, because function () {// code} has been explained in the "pre-compiled" stage, js will skip function () {// code} and attempt to execute ();, so an error will be reported;
When js executes (function {// code}) ();, because (function {// code}) is an expression, js will solve it to get the return value, because the return value is a function, when (); is encountered, it will be executed.

In addition, the method for converting a function to an expression does not have to rely on the grouping operator (). We can also use the void operator ,~ Operator ,! Operator ......

For example:

! Function () {alert ("Alternative anonymous function self-execution ");}();

Anonymous functions and closures

The English word closure of closures is a very important part of JavaScript knowledge, because using closures can greatly reduce the amount of our code and make our code look clearer, in short, the function is very powerful.

The meaning of the closure: To put it bluntly, it is the nesting of the function. The inner function can use all the variables of the outer function, even if the outer function has been executed (this involves the JavaScript scope chain ).

Function checkClosure () {var str = 'rain-Man'; setTimeout (function () {alert (str) ;}// this is an anonymous function, 2000 );} checkClosure ();

This example looks very simple. After careful analysis, there are still many knowledge points in its execution process: the execution of the checkClosure function is instantaneous (it may only take 0.00001 milliseconds ), A variable str is created in the checkClosure function. After the checkClosure is executed, str is not released because the anonymous function in setTimeout has reference to str. After 2 seconds, str is released after the anonymous function in the function is executed.

Use closures to optimize code:

Function forTimeout (x, y) {alert (x + y);} function delay (x, y, time) {setTimeout ('fortimeout ('+ x + ', '+ y +') ', time);}/*** the preceding delay function is hard to read and easy to write, however, if closure is used, the code can be clearer. * function delay (x, y, time) {* setTimeout (* function () {* forTimeout (x, y )*}*, time );*}*/

The biggest use of anonymous functions is to create closures (one of the features of the JavaScript language) and build namespaces to reduce the use of global variables.

Var oEvent ={}; (function () {var addEvent = function () {/* code implementation omitted */}; function removeEvent () {} oEvent. addEvent = addEvent; oEvent. removeEvent = removeEvent ;})();

In this Code, the functions addEvent and removeEvent are both local variables, but we can use the global variable oEvent, which greatly reduces the use of global variables and enhances the security of web pages.

We want to use this code:

OEvent. addEvent (document. getElementById ('box'), 'click', function () {}); var rainman = (function (x, y) {return x + y ;}) (2, 3);/*** can also be written in the following format, because the first bracket only helps us to read, but we do not recommend using the following format. * Var rainman = function (x, y) {* return x + y; *} (2, 3 );

Here we create a variable rainman and initialize it to 5 by directly calling an anonymous function. This is sometimes very useful.

var outer = null; (function(){ var one = 1; function inner (){ one += 1; alert(one); } outer = inner; })(); outer(); //2 outer(); //3 outer(); //4

The variable one in this code is a local variable (because it is defined in a function), so it cannot be accessed externally. But here we have created the inner function. The inner function can access the variable one and reference the global variable outer to the inner. Therefore, the incremental result is displayed when outer is called three times.

Note:

1 The closure allows the inner function to reference the variable in the parent function, but the variable is the final value.

/** * <body> * <ul> * <li>one</li> * <li>two</li> * <li>three</li> * <li>one</li> * </ul> */ var lists = document.getElementsByTagName('li'); for(var i = 0 , len = lists.length ; i < len ; i++){ lists[ i ].onmouseover = function(){ alert(i); }; }

You will find that when the mouse moves over each <li> element, 4 is always displayed, instead of the expected element subscript. Why? Note: (final value ). Obviously, this interpretation is too simple. When the mouseover event calls the listening function, first check whether I is defined in the anonymous function () {alert (I, the result is not defined. Therefore, it will look up, the search result is defined, and the I value is 4 (The I value after the loop); therefore, in the end, 4 is displayed each time.

Solution 1:

var lists = document.getElementsByTagName('li'); for(var i = 0 , len = lists.length ; i < len ; i++){ (function(index){ lists[ index ].onmouseover = function(){ alert(index); }; })(i); }

Solution 2:

Var lists = document. getElementsByTagName ('lil'); for (var I = 0, len = lists. length; I <len; I ++) {lists [I]. $ index = I; // record the subscript lists [I] by binding $ index to the Dom element. onmouseover = function () {alert (this. $ index );};}

Solution 3:

function eventListener(list, index){ list.onmouseover = function(){ alert(index); }; } var lists = document.getElementsByTagName('li'); for(var i = 0 , len = lists.length ; i < len ; i++){ eventListener(lists[ i ] , i); }

2. Memory leakage

The use of closures can easily lead to memory leakage in the browser. In severe cases, the browser will crash.

Articles you may be interested in:
  • Create and call methods of anonymous functions in js
  • JavaScript anonymous functions and closures
  • Example of calling js anonymous functions (diverse forms)
  • Callback examples of callback functions and anonymous functions in Javascript
  • Example of javascript anonymous Functions
  • Introduction to anonymous functions in js
  • JavaScript anonymous functions and closures)
  • N writing methods of anonymous functions in js
  • Understanding of javascript anonymous functions (thorough Version)
  • Javascript anonymous function Summary
  • Description of Javascript anonymous Functions

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.