This article mainly introduces some of the techniques used in function (the previous article), using function features can write a lot of very interesting code, this article mainly includes: callback mode, configuration object, return function, distribution program, Curry (currying). callback function in JavaScript, when a function A is one of the other parameters of function B, function A is called a callback function, that is, a can be executed within the period of function B (start, middle, and end). For example, there is a function for generating nodevarComplexcomputation =function() {/*internal processing, and returns a node*/There is a findnodes function declaration to find all the nodes and then execute the code through the callback callback. varFindnodes =function(callback) {varnodes = [];varnode =complexcomputation ();//if the callback function is available, execute itif(typeofcallback = = = "function") {Callback (node);} Nodes.push (node);returnnodes;}; As for the definition of callback, we can define it in advance to use://Define callbackvarHide =function(node) {Node.style.display= "None";};//find node, and then hide all of the nodevarHiddennodes =findnodes (hide); You can also use anonymous definitions directly at the time of invocation, as follows://defining callback with anonymous functionsvarBlocknodes = Findnodes (function(node) {Node.style.display= ' Block ';}); We usually use the most, estimated on the number of jquery Ajax methods of invocation, through the done/faild defines the callback so that it can be processed further when the AJAX call succeeds or fails, as follows (this code is based on version jquery1.8):varMenuId = $ ("Ul.nav"). First (). attr ("id"));varRequest =$.ajax ({URL:"Script.php", type:"POST", data: {Id:menuid}, DataType:"HTML"});//callback handling when the call succeedsRequest.done (function(msg) {$ ("#log"). HTML (msg);});//callback handling when a call failsRequest.fail (function(JQXHR, textstatus) {alert ("Request failed:" +textstatus);}); Configuration Object if a function (or method) parameter has only one parameter, and the argument is the object literal, we call this pattern the configuration object pattern. For example, the following code:varconf ={username:"Shichuan", First:"Chuan", Last:"Shi"};addperson (conf); Within Addperson, you can freely use the value of conf, which is commonly used for initialization work, such as the Ajaxsetup in jquery, which is implemented in this way://set the initial value beforehand.$.ajaxsetup ({URL:"/xmlhttp/", Global:false, type:"POST" });//and then call$.ajax ({data:mydata}); In addition, a lot of jquery plug-ins also have this form of communication, but also can not be passed, when the default value is used. Returns a function that returns a function that is the return value of one function, or a new function that is flexibly created according to a particular condition, as shown in the following example code:varSetup =function() {Console.log (1); return function() {Console.log (2); };};//Call the Setup functionvarmy = Setup ();//Output 1My ();//Output 2//or it can be called directly orsetup () (), or you can use the properties of the closure to record a private counter number in the Setup function, which is used to increment the counter each time, with the following code:varSetup =function () { varCount = 0; return function () { return++count; };};//usagevarNext =setup (); next ();//returns 1Next ();//returns 2Next ();//returns 3biased application here, in fact, the parameters of the incoming work separately, in some cases a series of operations may have one or several parameters are always exactly the same, then we can first define a partial function, and then go to execute this function (the execution of the remaining different parameters). For example, the code is as follows:varPartialany = (function(APs) {//The function is the result of your self-executing function expression, and assigns the value to the Partialany variable functionfunc (FN) {varArgsorig = Aps.call (arguments, 1); return function () { varargs =[], argspartial=Aps.call (arguments), I= 0; //the original parameter set of all variables, //If the argument is a partialany._ placeholder, the value corresponding to the next function parameter is used //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 extra arguments, add to the trailer returnFn.apply ( This, Args.concat (argspartial)); }; } //for placeholder SettingsFunc._ = {}; returnfunc;}) (Array.prototype.slice), using the following methods://Defining handler FunctionsfunctionHex (R, G, b) {return' # ' + R + G +b;}//define a partial function, the first parameter r of hex as the constant parameter value FFvarRedMax = Partialany (hex, ' FF ', Partialany._, partialany._);//The new function RedMax is called as follows, only 2 parameters are passed in:Console.log (RedMax (' 11 ', ' 22 '));//"#ff1122"If you think partialany._ is too long, you can use __ instead of OH. 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 ')); It's a lot simpler to use. Curryingcurrying is a feature of functional programming that transforms the processing of multiple parameters into the processing of a single parameter, similar to a chained invocation. To give an example of a simple add function:functionAdd (x, y) {varOLDX = x, Oldy =y; if(typeofOldy = = = "undefined") {//Partial return function(newy) {returnOLDX +Newy; } } returnX +y;} This can be called in a variety of ways, such as://TesttypeofAdd (5);//"function"Add (3) (4);//7//You can also call thisvaradd2000 = Add (2000); add2000 (10);// .Next, let's define a more general-purpose currying function://The first parameter is the function to be applied, and the second parameter is the minimum number of arguments that need to be passed infunctionCurry (func, Minargs) {if(Minargs = =undefined) {Minargs= 1; } functionFuncwithargsfrozen (Frozenargs) {return function () { //optimized processing, if no arguments are called, returns the function itself varargs =Array.prototype.slice.call (arguments); varNewargs =Frozenargs.concat (args); if(Newargs.length >=Minargs) { returnFunc.apply ( This, Newargs); } Else { returnFuncwithargsfrozen (Newargs); } }; } returnFuncwithargsfrozen ([]);} In this way, we can define our business behavior arbitrarily, such as defining addition:varplus = Curry (function () { varresult = 0; for(vari = 0; i < arguments.length; ++i) {result+=Arguments[i]; } returnresult;},2), the use of the way, the real variety of wow. Plus (3, 2)//Normal CallPlus (3)//partial application, return a function (the return value is the value of the parameter)Plus (3) (2)//Full Application (return 5)Plus () (3) () () (2)//returns 5Plus (3, 2, 4, 5)//can receive multiple parametersPlus (3) (2, 3, 5)//similarlyHere is an example of subtractionvarminus = Curry (function(x) {varresult =x; for(vari = 1; i < arguments.length; ++i) {result-=Arguments[i]; } returnresult;},2) or if you want to swap the order of the parameters, you can definevarFlip = Curry (function(func) {returnCurryfunction(A, b) {returnfunc (b, a); }, 2);}); For more information, refer to the following address: http://www.cnblogs.com/rubylouvre/archive/2009/11/09/1598761.htmlhttp://www.cnblogs.com/sanshi/archive/2009/02/17/javascript_currying.htmlsummarizing the functions in JavaScript has a number of special effects, you can use closures and arguments parameter features to implement many different tricks, and the next we will continue to introduce the technique of initializing with function. Reference address: http://shichuan.github.com/javascript-patterns/#function-patternssynchronization and recommendation this article has been synchronized to the directory index: in-depth understanding of JavaScript series in-depth understanding of the JavaScript series, including the original, translation, reprint and other types of articles, if it is useful to you, please recommend supporting a, to the power of the uncle writing.
In-depth understanding of the JavaScript series (*): function mode (previous)