Detailed description and examples of JavaScript function modes, and detailed description of javascript

Source: Internet
Author: User

Detailed description and examples of JavaScript function modes, and detailed description of javascript

The function of the JavaScript design pattern is to improve code reusability and readability, so that the code can be easily maintained and extended.

In javascript, a function is a type of object, which means that it can be passed to other functions as a parameter. In addition, a function can also provide a scope.

Syntax for creating a function

Name function expression

// Name function expression var add = function add (a, B) {return a + B ;}; var foo = function bar () {console. log (foo = bar) ;}; foo (); // true

It can be seen that they reference the same function, but this is only valid in the function body.

var foo = function bar() {};console.log(foo === bar);//ReferenceError: bar is not defined

However, you cannot call this function by calling bar.

var foo = (function bar() { console.log(foo === bar);})();//false

Function expression

// Also known as the anonymous function var add = function (a, B) {return a + B ;};

The value assigned to the add variable is the function definition itself. In this way, add becomes a function that can be called anywhere.

Function Declaration

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.

The difference between declarative functions and function expressions is that during the JS pre-compilation period, declarative functions are extracted first before js code is executed in order:

Console. log (f1); // [Function: f1]
Console. log (f2); // undefined, Javascript is not fully interpreted and executed in order. Instead, Javascript is pre-compiled before interpretation. During the pre-compilation process, the defined functions are preferentially executed.

function f1(){ console.log("I am f1");}var f2 = function (){ console.log("I am f2");};

Since all declared functions are constructed at the global scope, all declared functions are properties of window objects. This shows why we declare functions wherever they are, declaring a function eventually belongs to the window object.

In javascript, any anonymous function is a window object. When defining an anonymous function, it will return its own memory address. If a variable receives the memory address, the anonymous function can be used in the program, because anonymous functions are defined and assigned values during the Global execution environment construction, this of anonymous functions is also a window object.

var f2 = function (){ console.log("I am f2");};console.log(f2());//I am f2(function(){ console.log(this === window);//true})();

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:

<Script type = "text/javascript"> // global 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 variable foo and the implementer are promoted to function foo () {alert ('local foo! Raise ');} // only the variable bar is promoted, and the function implementation part is not upgraded to var bar = function () {alert ('lower 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:

<Script> (function () {var a = 1; return function () {alert (2) ;}}() (); // pop up 2, the first parentheses are self-executed, and the second parentheses are used to execute internal anonymous functions </script>

Mode 2: Orientation of Self-executed function variables

<Script type = "text/javascript"> var result = (function () {return 2 ;}) (); // The alert (result) function has been executed here ); // result points to the returned value 2 of the Self-executed function. If result () is displayed, an error occurs. </script>

Mode 3: Nested Functions

<Script type = "text/javascript"> var result = (function () {return 2 ;}) (); alert (result ()); // 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 behind the return statement will pop up; if it is abc (), the function after return is executed.

Mode 5: The function executes itself internally, recursively

// This is an self-executed function. The function executes itself internally, and the 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:

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:

<script type="text/javascript"> var call = function(){  console.log("100ms 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:

<Script type = "text/javascript"> // curry-based add () function add (x, y) {var oldx = x, oldy = y; if (typeof oldy = "undefined") {return function (newy) {return oldx + newy ;}/// return x + y is fully applied ;} // 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:

<Script type = "text/javascript"> // normal function add (x, y) {return x + y ;} // curry a function to obtain a new function var newadd = test (add, 5); newadd (4); // 9 // another choice, directly call the new function 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.

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.