_javascript techniques for functional patterns in JavaScript

Source: Internet
Author: User
Tags anonymous closure event listener function definition

The role of JavaScript design patterns is to improve the reusability and readability of your code, making it easier to maintain and extend your code

In JavaScript, a function is a class of objects, which means that he can pass as arguments to other functions, and functions can also provide scopes.

syntax for creating functions

named function expression

Copy Code code as follows:

named function expression
var add = function Add (a,b) {
return a+b;
};

function expression
Copy Code code as follows:

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

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

Declaration of functions

Copy Code code as follows:

function foo () {
code here
}//No semicolon is required here

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

function declarations and expressions

Elevation of functions (hoisting)

The behavior of a function declaration is not the same as a named function expression, which differs in elevation (hoisting) behavior by looking at the following example:

Copy Code code as follows:

<script type= "Text/javascript" >
Global functions
function foo () {alert ("Global Foo!");}
function bar () {alert (' Global Bar ');}

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

Foo ();//local foo!
Bar ();//typeerror: ' Undefined ' is not a function

Variable foo and the implementation is promoted
function foo () {
Alert (' local foo! ');
}

Only the variable bar is promoted and the function implementation part is not promoted
var bar = function () {
Alert (' local bar! ');
};
}
Hoist ();
</script>


For all variables, no matter where the function body is declared, it is promoted internally to the top of the function. This is true for functions, because functions are simply objects assigned to variables.

Ascension, as the name suggests, is the following things mentioned above. In JS, it is to elevate the definition in the following (variable or function) to the previous definition. As you can see from the example above, the Foo and bar inside the function hoist are moved to the top, overwriting the global Foo and bar functions. The difference between a local function bar and Foo is that Foo is promoted to the top and works, and the definition of bar () is not promoted, only its declarations are elevated, so when the bar () is executed, the result is displayed as undefined rather than as a function.

Instant function mode

Functions are also objects, so they can serve as return values. The advantage of using a self-executing function is to declare an anonymous function immediately, to avoid defining a function that is not used once, and to exempt from the problem of naming conflicts, there is no namespace concept in JS, so it is very easy to have the function name conflict, once the naming conflict is final.

Mode one:

Copy Code code as follows:

<script>
(function () {
var a = 1;
return function () {
Alert (2);
};
} () ());//Eject 2, the first parenthesis executes, and the second parenthesis executes the internal anonymous function
</script>

mode Two: The direction of the self-executing function variable
Copy Code code as follows:

<script type= "Text/javascript" >
var result = (function () {
return 2;
}) ();//The function has been executed here

alert (result);//result points to the return value of 2 from the self-executing function;
</script>


mode three: nested functions
Copy Code code as follows:

<script type= "Text/javascript" >
var result = (function () {
return function () {
return 2;
};
})();

Alert (Result ()),//alert (Result) when pop-up 2;alert (Result ()) pop-up function () {return 2}
</script>

Mode four: The self-execution function assigns its return value to the variable

Copy Code code as follows:

var abc = (function () {
var a = 1;
return function () {
return ++a;
}
}) ()//The function that returns the return is returned by the execution function to the variable
Alert (ABC ());//If alert (ABC) pops up the code following the return statement, and if it is ABC (), the function after return is executed

mode five: function inside execute itself, recursion
Copy Code code as follows:

This is a self executing function that executes itself within the function, recursively
Function ABC () {ABC ();}

Callback mode

callback function: When you pass a function write () as a parameter to another function called (), then at some point call () may execute (or invoke) write (). In this case, write () is called the callback function (callback functions).

Asynchronous Event Listener

The callback pattern has many uses, for example, when attaching an event listener to an element on the page, it actually provides a pointer to a callback function that will be invoked when the event occurs. Such as:

Copy Code code as follows:

Document.addeventlistener ("click", Console.log,false);

The code example above shows the Console.log () of a document that is passed in bubbling mode to the callback function ().

JavaScript is especially useful for event-driven programming, because the callback mode supports programs to run asynchronously.

Timeout

Another example of using the callback pattern is when using a browser's window object to provide a time-out method: SetTimeout () and setinterval (), such as:

Copy Code code as follows:

<script type= "Text/javascript" >
var call = function () {
Console.log ("100ms would be asked ...");
};
settimeout (call, 100);
</script>

callback mode in the library

When designing a JS library, the callback function comes in handy, and a library's code should use reusable code whenever possible, and callbacks can help achieve this generalization. When we design a large JS library, in fact, users do not need most of these functions, and we can focus on the core functions and provide "hook form" callback functions, which will make it easier to build, expand, and custom library methods

of curry

Curry technology is a technique that transforms a function into a new simplified (less acceptable parameter) function by populating multiple parameters into the function body. ——— "Proficient in JavaScript"

In simple terms, curry is a process of transformation in which we perform function transformations. The following example:

Copy Code code 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;
};
}
Fully applied
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 you call Add () for the first time, it creates a closure for the internal function that is returned. The closure stores the original x and Y values in the private variables oldx and Oldy.

Now, we will be able to use any function curry common methods, such as:

Copy Code code as follows:

<script type= "Text/javascript" >
normal function
function Add (x,y) {
return x + y;
}
Curry a function to get a new function
var newadd = Test (add,5);
Newadd (4);//9

Another option, calling a new function directly
Test (add,6) (7);//Output 13
</script>


When to use curry

When it is discovered that the same function is being invoked, and that most of the arguments passed are the same, then the function may be a good candidate 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.