Deep understanding of JavaScript series (49): function mode (Part 1)

Source: Internet
Author: User
Introduction

This article mainly introduces some of the functions used (Part I). Using the function features, you can write a lot of interestingCodeThis article mainly includes: callback mode, configuration object, return function, distributionProgramAnd currying ).

Callback Function

In JavaScript, when function a acts as one of the parameters of function B, function a is called a callback function, that is, a can be executed within the period of function B (START, center, and end time ).

For example, a function is used to generate a node.

 
VaRComplexcomputation =Function(){/*Internal processing, and return a node*/};

There is a findnodes function declaration used to find all nodes and then execute code through the callback.

VaRFindnodes =Function(Callback ){VaRNodes =[];VaRNode =Complexcomputation ();//If the callback function is available, run it. If(TypeofCallback ="Function") {Callback (node);} nodes. Push (node );ReturnNodes ;};

The definition of callback can be defined in advance:

//Define callback VaRHide =Function (node) {node. style. Display="None";};//Search for nodes and hide all nodes VaRHiddennodes = findnodes (hide );

You can also use the anonymous definition directly during the call, as shown below:

//Use an anonymous function to define callback VaRBlocknodes =Findnodes (function (node) {node. style. Display='Block';});

We usually use the most, and it is estimated that jquery's Ajax method is called. By defining callback on done/faild, we can further process Ajax call success or failure, the Code is as follows (this code is based on jquery1.8 ):

 VaR Menuid = $ ( "  Ul. Nav  " ). First (). ATTR ( "  ID  " );  VaR Request = $. Ajax ({URL:  "  Script. php  "  , Type:  "  Post  "  , Data: {ID: menuid}, datatype:  "  Html  "  });  // Callback processing when the call is successful   Request. Done (function (MSG) {$ (  "  # Log  "  Pai.html (MSG );});  //  Callback processing when the call fails   Request. Fail (function (jqxhr, textstatus) {alert (  "  Request failed:  " + Textstatus );}); 

Configuration object

If a function (or method) has only one parameter and the parameter is an object literal, we call this mode the configuration object mode. For example, the following code:

VaRConf ={Username:"ShiChuan", First:"Chuan", Last:"Shi"}; Addperson (CONF );

In addperson, you can use the conf value at will, which is generally used for initialization. For example, ajaxsetup in jquery is implemented in this way:

//Set the initial value in advance $. Ajaxsetup ({URL:"/XMLHTTP/",Global:False, Type:"Post"});//And then call$. Ajax ({data: mydata });

In addition, many jquery plug-ins also use this form of parameter passing, but they can also be left blank. If they are left blank, the default value is used.

Return Function

A return function is a function that returns another function or creates a new function based on specific conditions. The sample code is as follows:

VaRSetup =Function() {Console. Log (1);ReturnFunction () {console. Log (2);};};//Call the setup Function VaRMy = setup ();//Output 1My ();//Output 2
// Or you can call it directly.
Setup ()();

Alternatively, you can use the closure feature to record a private counter number in the setup function and add a counter by calling each call. The Code is as follows:

VaRSetup =Function(){VaRCount =0;ReturnFunction (){Return++Count ;};};//Usage VaRNext =Setup (); next ();//Return 1Next ();//Returns 2Next ();//Return 3

Partial application

Here, the partial application actually separates the input parameters. Sometimes, some or several parameters may always be the same in a series of operations, then we can define a partial function and then execute the function (the remaining parameters are input during execution ).

For example, the Code is as follows:

 VaR Partialany = (Function (APS ){  //  This function is the result of your self-executed function expression and is assigned to the partialany variable.   FunctionFunc (FN ){  VaR Argsorig = APs. Call (arguments, 1  );  Return  Function(){ VaR ARGs = [], Argspartial = APs. Call (arguments), I = 0  ;  //  All original parameter sets of the variable,  //  If the parameter is a placeholder for partialany. _, use the value corresponding to the next function parameter.  //  Otherwise, use the value in the original parameter.               For (; I <argsorig. length; I ++ ) {ARGs [I] = Argsorig [I] = Func ._ ? Argspartial. Shift (): argsorig [I];}  //  If there are any redundant parameters, add them to the end               Return FN. Apply ( This  , ArgS. Concat (argspartial ));};}  //  Used for placeholder settings Func. _ = {};  Return  Func;}) (array. Prototype. Slice ); 

The usage is as follows:

 //  Define processing functions   Function hex (R, G, B ){  Return   '  #  ' + R + G + B ;}  //  Defines partial functions, and uses the first parameter r of hex as the constant parameter value FF   VaR Redmax = partialany (Hex, '  FF  '  , Partialany. _, partialany ._); //  The call method of the new function redmax is as follows. You only need to input two parameters: Console. Log (redmax ( '  11  ' , '  22  ' )); //  "# Ff1122" 

If you think partialany. _ is too long, you can replace it.

VaR_ =Partialany ._;VaRGreenmax = partialany (hex ,__, 'ff'); Console. Log (greenmax ('33', '44'));VaRBluemax = partialany (hex ,__ ,__, 'ff'); Console. Log (bluemax ('55', '66'));VaRMagentamax = partialany (Hex, 'ff ',__, 'ff'); Console. Log (magentamax ('77 '));

This method is much simpler.

Currying

Currying is a feature of functional programming. It converts processing of multiple parameters into processing of a single parameter, similar to chained calling.

Here is an example of a simple add function:

FunctionAdd (x, y ){VaROldx = x, Oldy =Y;If(TypeofOldy = "undefined "){//PartialReturn Function(Newy ){ReturnOldx +Newy ;}}ReturnX +Y ;}

In this way, there can be multiple calling methods, such:

//Test TypeofAdd (5 );//"Function"Add (3) (4 );//7//You can also call VaRAdd2000 = add (2000); Add2000 (10 );//2010

Next, we will define a more general currying function:

 //  The first parameter is the function to be applied, and the second parameter is the minimum number of parameters to be passed in.   Function  Curry (func, minargs ){ If (Minargs = Undefined) {minargs = 1 ;}  Function  Funcwithargsfrozen (frozenargs ){  Return   Function  (){  //  Optimization. If there is no parameter during the call, the function itself is returned.               VaR ARGs = Array. Prototype. Slice. Call (arguments );  VaR Newargs =Frozenargs. Concat (ARGs );  If (Newargs. length> = Minargs ){  Return Func. Apply ( This  , Newargs );}  Else  {  Return  Funcwithargsfrozen (newargs );}};}  Return  Funcwithargsfrozen ([]);} 

In this way, we can define our business behavior at will, such as the addition:

VaRPlus = curry (Function(){VaRResult = 0;For(VaRI = 0; I <arguments. length; ++I) {result+ =Arguments [I];}ReturnResult ;},2 );

There are a variety of real usage methods.

Plus (3, 2)//Normal callPlus (3)//Partial application, returns a function (return value is 3 + parameter value)Plus (3) (2)//Complete application (return 5)Plus () (3) (2)//Return 5Plus (3, 2, 4, 5)//Can receive multiple parametersPlus (3) (2, 3, 5)//Likewise

The following is an example of subtraction.

VaRMinus = curry (Function(X ){VaRResult =X;For(VaRI = 1; I <arguments. length; ++I) {result-=Arguments [I];}ReturnResult ;},2 );

Or if you want to switch the order of parameters, you can define

VaRFlip = curry (Function(Func ){ReturnCurry (Function(A, B ){ReturnFunc (B, );},2);});

For more information, see the following link:

Http://www.cnblogs.com/rubylouvre/archive/2009/11/09/1598761.html

Http://www.cnblogs.com/sanshi/archive/2009/02/17/javascript_currying.html

Summary

Functions in Javascript have many special functions. You can use the closure and arguments parameter features to implement many different techniques. Next we will continue to introduce the function initialization techniques.

Reference: http://shichuan.github.com/javascript-patterns/#function-patterns

 

Reprinted:

Http://www.cnblogs.com/TomXu

 

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.