Deep understanding of JavaScript Series: function mode (previous) _ Basics

Source: Internet
Author: User
Tags anonymous

Introduced

This article mainly introduces the function aspect uses some techniques (above), uses the function characteristic to be possible to write many very interesting code, this article mainly includes: The callback pattern, the configuration object, the return function, the distribution program, the currying.

callback function

In JavaScript, when a function A is one of the arguments of another function B, function A is called a callback function, that is, a can be executed within the cycle of function B (start, middle, and end).

For example, there is a function to generate node

Copy Code code as follows:

var complexcomputation = 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.
Copy Code code as follows:

var findnodes = function (callback) {
var nodes = [];

var node = complexcomputation ();

If the callback function is available, execute it
if (typeof callback = = "function") {
Callback (node);
}

Nodes.push (node);
return nodes;
};

As for the definition of callback, we can define it in advance:

Copy Code code as follows:

Define Callback
var hide = function (node) {
Node.style.display = "None";
};

Find node, and then hide all node
var hiddennodes = findnodes (hide);

You can also use anonymous definitions directly at the time of the call, as follows:

Copy Code code as follows:

Using anonymous functions to define callback
var blocknodes = findnodes (function (node) {
Node.style.display = ' block ';
});

We usually use the most, estimated on the number of jquery Ajax methods of the call, by defining the callback on the Done/faild, so that when the AJAX call succeeds or fail to do further processing, the code is as follows (this code is based on the jquery1.8 version):
Copy Code code as follows:

var MenuID = $ ("Ul.nav").------------attr ("id");
var request = $.ajax ({
URL: "script.php",
Type: "POST",
Data: {Id:menuid},
DataType: "HTML"
});

Callback processing when the call succeeds
Request.done (function (msg) {
$ ("#log"). HTML (msg);
});

Callback processing when the call fails
Request.fail (function (JQXHR, textstatus) {
Alert ("Request failed:" + textstatus);
});

Configuration Object

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

Copy Code code as follows:

var conf = {
Username: "Shichuan",
A: "Chuan",
Last: "Shi"
};
Addperson (conf);

Within Addperson, you can use the value of conf at will, typically for initialization, such as the Ajaxsetup in jquery, which is the way to do it:
Copy Code code as follows:

Set initial values in advance.
$.ajaxsetup ({
URL: "/xmlhttp/",
Global:false,
Type: "POST"

});

and then call
$.ajax ({data:mydata});

In addition, many jquery plug-ins have this form of reference, but also can not pass, do not pass when the default value is used.

return function

return function, refers to the return value of a function is another function, or based on specific conditions to create a flexible new function, the sample code is as follows:

Copy Code code as follows:

var setup = function () {
Console.log (1);
return function () {
Console.log (2);
};
};

Calling the Setup function
var my = Setup (); Output 1
My (); Output 2
Or direct call can also be
Setup () ();


Alternatively, you can use the closure feature to record a private counter number in the Setup function, which is used to increase the counter by using the following code:
Copy Code code as follows:

var setup = function () {
var count = 0;
return function () {
return ++count;
};
};

Usage
var next = Setup ();
Next (); Return 1
Next (); Return 2
Next (); Return 3

Partial application

The biased application here, in fact, is the introduction of the parameters of the work separately, in some cases a series of operations may have a certain or several parameters are always exactly the same, then we can define a partial function, and then to execute the function (passed in the remaining different parameters).

For example, the code is as follows:

Copy Code code as follows:

var Partialany = (function (APS) {

   //The function is the result of your own function expression and is assigned to the Partialany variable
    function func (FN) {
         var argsorig = aps.call (arguments, 1);
        return function () {
             var args = [],
                 argspartial = aps.call (arguments),
                 i = 0;

           //variable all original parameter sets,
            //If the parameter is a partialany._ placeholder, use the value of 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 extra arguments, add to the tail
Return fn.apply (This, Args.concat (argspartial));
};
}

For placeholder settings
Func._ = {};

return func;
}) (Array.prototype.slice);

The use of the following methods:

Copy Code code as follows:

Defining a handler function
function Hex (r, G, b) {
Return ' # ' + R + G + B;
}

Defines the offset function, hex the first parameter R as the invariant parameter value FF
var RedMax = Partialany (hex, ' ff ', partialany._, partialany._);

The new function RedMax is invoked as follows, with only 2 parameters passed in:
Console.log (RedMax (' 11 ', ' 22 ')); "#ff1122"


If you think partialany._ is too long, you can use __ instead oh.
Copy Code code as follows:

var __ = partialany._;

var Greenmax = Partialany (hex, __, ' FF ');
Console.log (Greenmax (' 33 ', ' 44 '));

var BlueMax = Partialany (hex, __, __, ' FF ');
Console.log (BlueMax (' 55 ', ' 66 '));

var Magentamax = Partialany (hex, ' FF ', __, ' FF ');
Console.log (Magentamax (' 77 '));


It's a lot simpler to use.

Currying

Currying is a feature of functional programming that converts the processing of multiple parameters into a single parameter processing, similar to a chained call.

Give an example of a simple add function:

Copy Code code as follows:

function add (x, y) {
var oldx = x, Oldy = y;
if (typeof Oldy = = "undefined") {//partial
return function (Newy) {
return OLDX + newy;
}
}
return x + y;
}

This can be invoked in a variety of ways, such as:
Copy Code code as follows:

Test
typeof Add (5); "Function"
Add (3) (4); 7

You can also call this
var add2000 = Add (2000);
add2000 (10); 2010


Next, let's define a more general currying function:
Copy Code code as follows:

The first parameter is the function to be applied, and the second parameter is the minimum number of parameters that need to be passed in
function Curry (func, Minargs) {
if (Minargs = = undefined) {
Minargs = 1;
}

function Funcwithargsfrozen (Frozenargs) {
return function () {
Optimization processing, if the call has no arguments, returns the function itself
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 defining addition:

Copy Code code as follows:

var plus = Curry (function () {
var result = 0;
for (var i = 0; i < arguments.length; ++i) {
result = Arguments[i];
}
return result;
}, 2);

The use of the way, the real variety Wow.
Copy Code code as follows:

Plus (3, 2)//Normal call
Plus (3)//Bias application, return a function (return value is 3+ parameter value)
Plus (3) (2)//Full application (return 5)
Plus () (3) () () (2)//return 5
Plus (3, 2, 4, 5)//can receive multiple parameters
Plus (3) (2, 3, 5)//Empathy

The following is an example of subtraction
Copy Code code as follows:

var minus = Curry (function (x) {
var result = x;
for (var i = 1; i < arguments.length; ++i) {
Result-= Arguments[i];
}
return result;
}, 2);

Or if you want to switch the order of the parameters, you can define this
Copy Code code as follows:

var flip = Curry (function (func) {
Return Curry (function (A, b) {
return func (b, a);
}, 2);
});

Summarize

Functions in JavaScript have a number of special effects that allow you to implement many different techniques with closures and arguments parameter features, and we'll continue to introduce the techniques of initializing functions using function.

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.