JavaScript function mode

Source: Internet
Author: User

JavaScript function mode

Syntax for creating a function

Name function expression

 

The Code is as follows:


// Name function expression
Var add = function add (a, B ){
Return a + B;
};

 

Function expression

 

The Code is as follows:


// Also known as anonymous Functions
Var add = function (a, B ){
Return a + B;
};

 

Function Declaration

 

Copy the Code as follows:


Function foo (){
// Code here
} // You do not need a semicolon here

 

In the trailing semicolon, the function expression should always use the semicolon, and the declaration of the function does not need to end with the semicolon.

Function declaration and Expression

Hoisting)

The behavior of the function declaration is not equivalent to the name function expression. The difference is that the hoisting behavior. See the following example:

 

The Code is as follows:


<Script type = "text/javascript">
// Global functions
Function foo () {alert ("global foo! ");}
Function bar () {alert ('your global bar ');}

 

Function hoist (){
Console. log (typeof foo); // function
Console. log (typeof bar); // undefined

Foo (); // local foo!
Bar (); // TypeError: 'undefined' is not a function

// The foo variable and the implementer variable are promoted.
Function foo (){
Alert ('local foo! Comment ');
}

// Only the variable bar is promoted, and the function implementation is not promoted.
Var bar = function (){
Alert ('your local bar! ');
};
}
Hoist ();
</Script>

 

All variables, no matter where they are declared in the function body, are internally promoted to the top of the function. For general functions, the reason is that the function is only assigned to the object of the variable.

As the name implies, the promotion refers to the following. In JS, the things (variables or functions) defined below are upgraded to the previous definition. As shown in the preceding example, the foo and bar in the hoist function move to the top to overwrite the global foo and bar functions. The difference between the local function bar and foo is that foo is promoted to the top and can run normally, while the bar () definition is not improved, only its declaration is promoted. Therefore, when bar () is executed, the result is undefined instead of used as a function.

Real-time function mode

Functions are also objects, so they can be used as return values. The advantage of using a self-executed function is to directly declare an anonymous function and use it immediately, saving the need to define a function that is not used once and avoiding name conflicts, js does not have the namespace concept, so it is easy to have a function name conflict. Once a name conflict occurs, the last declaration prevails.

Mode 1:

 

The Code is as follows:


<Script>
(Function (){
Var a = 1;
Return function (){
Alert (2 );
};
} (); // Pop-up 2. The first parentheses are self-executed, and the second parentheses are internal anonymous functions.
</Script>

 

Mode 2: Orientation of Self-executed function variables

 

The Code is as follows:


<Script type = "text/javascript">
Var result = (function (){
Return 2;
}) (); // The function has been executed here

 

Alert (result); // result indicates the returned value of the Self-executed function. 2. If result () is displayed, an error occurs.
</Script>

 

Mode 3: Nested Functions

 

The Code is as follows:


<Script type = "text/javascript">
Var result = (function (){
Return function (){
Return 2;
};
})();

 

Alert (result (); // when alert (result) is displayed 2; When alert (result () is displayed function () {return 2}
</Script>

 

Mode 4: The self-executed function assigns its return value to the variable.

 

 

Var abc = (function (){
Var a = 1;
Return function (){
Return ++;
}
}) (); // The self-executed function returns the function after return to the variable
Alert (abc (); // if it is alert (abc), the Code following the return statement is displayed. If it is abc (), the function following the return statement is executed.

 

Mode 5: The function executes itself internally, recursively

 

The Code is as follows:


// This is a self-executed function. The function executes itself internally and is recursive.
Function abc () {abc ();}

 

Callback Mode

Callback Function: When you pass a function write () as a parameter to another function call (), call () may be executed (or called) at a certain time point) write (). In this case, write () is called the callback function ).

Asynchronous event listener

The callback mode has many functions. For example, when an event listener is appended to an element on the page, it actually provides a pointer to the callback function, this function will be called when an event occurs. For example:

 

The Code is as follows:


Document. addEventListener ("click", console. log, false );

 

The code example above demonstrates how to pass the event to the callback function console. log () in bubble mode when you click an event.

Javascript is especially suitable for event-driven programming, because the callback mode supports program running in asynchronous mode.

Timeout

Another example of using the callback mode is when the browser's window object provides the timeout Methods: setTimeout () and setInterval (), such:

 

The Code is as follows:


<Script type = "text/javascript">
Var call = function (){
Console. log ("100 ms will be asked... ");
};
SetTimeout (call, 100 );
</Script>

 

Callback mode in the library

When a js library is designed, callback functions will be used. The code of a library should use reusable code as much as possible, and callback can help achieve this generalization. When we design a huge js library, users do not actually need most of the functions, but we can focus on the core functions and provide callback functions in the "hook form, this makes it easier for us to build, scale, and customize library methods.

Curry

Curry technology is a technology that converts a function into a new simplified (fewer accepted parameters) function by filling multiple parameters into the function body. --- [Proficient in JavaScript]

To put it simply, Curry is a conversion process, that is, the process of executing function conversion. Example:

 

The Code is as follows:


<Script type = "text/javascript">
// Curry add () function
Function add (x, y ){
Var oldx = x, oldy = y;
If (typeof oldy = "undefined "){
Return function (newy ){
Return oldx + newy;
};
}
// Full application
Return x + y;
}
// Test
Typeof add (5); // output "function"
Add (3) (4); // 7
// Create and store a new function
Var add2000 = add (2000 );
Add2000 (10); // output 2010
</Script>


When add () is called for the first time, it creates a closure for the returned internal function. This closure stores the original x and y values in the private variables oldx and oldy.

 

Now, we can use a common method of any function, such:

 

The Code is as follows:


<Script type = "text/javascript">
// Common functions
Function add (x, y ){
Return x + y;
}
// Curry a function to obtain a new function
Var newadd = test (add, 5 );
Newadd (4); // 9

 

// Another option is to call the new function directly.
Test (add, 6) (7); // output 13
</Script>

 

When to use Curry

When we find that the same function is being called and the vast majority of passed parameters are the same, this function may be a good candidate parameter for Curry.

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.