JavaScript Design patterns and development practices

Source: Internet
Author: User

 What is a higher order function?

  A higher order function is a function that satisfies at least one of the following conditions:

1. Functions can be passed as parameters

2. function can be output as return value

  

  1. The function is passed as a parameter so that we can pull out part of the business logic that is easily changed , and put this part of the business in the function parameters, so that the changes and invariant parts of the business code can be separated. The common forms are:

  1) callback function

Common callbacks such as Ajax: when we use Ajax to make a request, but don't know exactly when the request is returned, we can use the callback to resolve the callback as a parameter into the Ajax request method, and so on after the request is completed.

function GetData (ID, callback) {    $.ajax ({        type: ' GET ',        URL: ' http://163.com/?getData= ' +id,        dataType : ' JSON ',        success:function (data) {            callback (data);        }}    )}

GetData (12345, function (data) {Console.log (data)})

The callback function can be used not only in asynchronous requests:

If we want to create 100 div nodes in the page and set these nodes to be hidden, we can do so

function Appenddiv () {for    (var i = 0; i <; i++) {        var div = document.createelement (' div ');        div.innerhtml = i;        Document.body.append (div);        Div.style.display = ' none ';    }} Appenddiv ()

It doesn't seem to be a problem, but when we change the requirements next time, the 100 div changes the background color, and the code is hard to reuse. We can do this:

function Appenddiv (callback) {for    (var i = 0; i <; i++) {        var div = document.createelement (' div ');        div.innerhtml = i;        Document.body.append (div);        if (callback && typeof callback = = = ' function ') {            callback (div)        }    }}appenddiv (function (node) {    node.style.display = ' None '})

By using callbacks, the business code will be in the callback function, you can pull out a part of the business code, the code reuse is very helpful. If you need to modify the requirements later, change the color, change the size, and so on only need to re-write callback function.

  2) Array.prototype.sort, the method takes a function as a parameter, which tells the collation of the array to implement different sorts by defining different methods, making the sort very flexible.

[1, 3, 4, 2].sort (function (A, b) {return a-B    ;}) Output [1, 2, 3, 4][1, 3, 4, 2].sort (function (A, b) {    return b-a;}) Output [4, 3, 2, 1]

 2. function as return value output

  1) Determine the type of data

As in the previous article http://www.cnblogs.com/ppforever/p/4362102.html to determine if a JS object is not an array, the function is returned as a value. Slightly expanded:

var istype = function (type) {        ///functions as return value returned as function    (obj) {        return Object.prototype.toString.call (obj = = = ' [object ' + Type + '] ';    }} var IsArray = istype (' Array '), var isstring = Istype (' String '), var isnumber = Istype (' number '), Console.log (IsArray ([1, 6, 3]))//true

We can also use circular statements to register the Istype method in bulk:

var type = {};for (var i = 0, type; type = [' String ', ' Array ', ' number '][i++];) {    (function (type) {        type[' is ' +type] = function (obj) {
         return Object.prototype.toString.call (obj) = = = ' [Object ' + type + '] '; } }) (type)} Type.isarray ([]); Truetype.isstring (' abc ');//truetype.isnumber (123);//truetype.isarray (123);//false

The above section mainly introduces the common forms of higher-order functions, and the next section focuses on advanced applications of higher-order functions.

  

JavaScript Design patterns and development practices

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.