JavaScript Design Patterns and development practices-reading notes (3) closures and Higher-order functions

Source: Internet
Author: User
Tags getscript

Closures (closure)

The formation of closures is closely related to the scope of variables and the life cycle of Variables.

The scope of a variable refers to the valid range of Variables.

Global variables and local variables.

In javascript, functions can be used to create function scopes.

The lifetime of the variable, the lifetime of the global variable is permanent, unless we actively destroy the global Variable.

For local variables declared with the var keyword in the function body, these local variables lose their value when exiting the function, and they are destroyed as the function call ENDS.

We can do a lot of wonderful work with Closures.

The role of Closures:

1. Amount of change of seal

Closures can help us to turn some variables that do not need to be exposed to a global variable into "private variables."

2. Continuation of local variable life

IMG objects are often used for data escalation, and we can turn the IMG variable into a closed packet to solve the problem of request Loss.

var report = ({    var imgs= [];     return function (src) {        varnew  Image ();        Imgs.push (img);         = src;    }}) ();

A complete object-oriented system can be implemented with Closures.
Implementing command mode with closures

Closures are a very powerful feature, but there are many misconceptions about it. A sensational argument is that closures can cause memory leaks, so minimize the use of Closures.

The use of closures is also relatively easy to form a circular reference, if the closure is relatively easy to form a circular reference, if the scope of the closure of the chain holds some Dom nodes, this time may cause memory leaks. But this is not a problem of closures in itself, nor is it a question of javascript.

Higher order functions

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

Functions can be passed as parameters;

The function can be output as a return Value.

function as a parameter pass

1. callback function

In the application of Ajax asynchronous requests, the use of callback functions is very frequent.

The application of the callback function is not only in the asynchronous request, when a function is not suitable for some requests, we can also turn these requests into a function, and pass it as a parameter to another function, "delegate" to another function to Execute.

2.array.prototype.sort

Array.prototype.sort accepts a function as a parameter, which in turn marshals the collation of the array Element. Our goal is to sort the array, which is the invariant part, and what rules to use to sort, is the variable part.

function is passed as a return value

1. Determine the type of data

2.getSingle

Example of a singleton pattern:

varGetsingle =function(fn) {varret; return function(){        returnRET | | (ret = Fn.apply ( this, AR;GUMENTS)) };};//the example of this higher order function, which passes the function as a parameter, and returns another function after the function executes. varGetScript = Getsingle (function(){    returndocument.createelement (' script ');});varSCRIPT1 =GetScript ();varScript2 =getScript (); Alert (script1= = = script2);//output: True

High-order functions for AOP

The main function of AOP (aspect-oriented Programming) is to pull out functions unrelated to the core business logic modules, which are usually related to business logic, such as log statistics, security control, exception handling, and so On. After these functions are removed, they are then incorporated into the business logic module in the form of "dynamic weaving". The benefit of doing this first is to maintain the pure and high cohesion of the business logic module, and secondly, it is convenient to reuse the function modules such as log statistics.

In the dynamic language of javascript, the implementation of AOP is simpler, which is the innate ability of javascript.

In general, implementing AOP in JavaScript refers to the "dynamic weaving" of a function into another function.

Application of the common higher order function

1.currying

function Currying. Currying is also called partial Evaluation. A curring function will first accept some parameters, after accepting these parameters, the function does not immediately evaluate, but continues to return another function, the parameters just passed in the function formed in the closure of the Save. Until the function is truly evaluated, all previously passed parameters are evaluated Once.

In the following example, the function iterates through the cost of the day of the month and evaluates the sum of them:

varcurrying =function(fn) {varargs = []; return function(){            if(arguments.length = = 0){                returnFn.apply ( this, args); }Else{[].push.apply (args,arguments); returnarguments.callee;    }        }    }; varCost = (function(){        varMoney = 0; return function(){             for(varI=0;l = arguments.length,i<l;i++) { money+=arguments[i]; }            returnmoney ;    }    })(); varCost = currying (cost);//Convert to currying functionCost (100);//not really evaluatedCost (200);//not really evaluatedCost (300);//not really evaluatedAlert (cost ());//evaluates and outputs

It is only when we execute cost () in the form of no parameters that we actually begin the evaluation calculation using all the previously saved Parameters.

2.uncurrying

Is there any way to extract the process of generalization this, uncurrying is used to solve this problem. The following code is one of the ways that Uncurrying is implemented:

function () {    varthis;     return function () {        var obj = Array.prototype.shift.call (arguments);         return self.apply (obj,arguements);    }
};

Another way to achieve this:

function () {    varthis;     return function () {        return  Function.prototype.call.apply (self,arguements);    }};

3. Function throttling

(1) a function can be called very frequently, causing large performance problems

The following scenario:

    1. Window.onresize Events
    2. MouseMove Events
    3. Upload Progress

(2) the principle of function throttling

Some event requests are ignored by time Period. It is clear that settimeout can be borrowed to do the job.

(3) code Implementation of function throttling

There are many kinds of code implementations for function throttling, and the following throttle function works by delaying the execution of the function that is about to be executed for a period of time with Settimeout.

  

    varThrottle =function(fn,interval) {var_self = fn,//Save a function call that needs to be deferredTimer//TimerFirsttime =true;//is it the first time that you call        return function(){            varargs =arguments, _me= this; if(firsttime) {//If this is the first call, there is no need to delay execution_self.apply (_me,args); returnFirsttime =false; }            if(timer) {//If the timer is still in, the previous deferred execution has not been completed                return false; } Timer= SetTimeout (function(){//delay execution for some timecleartimeout (timer); Timer=NULL;            _self.apply (_me,args); },interval|| 500);    };    }; Window.onresize= Throttle (function() {console.log (1); },500);

4. time-sharing function

An example is a list of QQ friends who create webqq. There are usually hundreds or thousands of friends in the list, and if a friend is using a node to represent it, we may want to create hundreds or thousands of nodes in the page when we render the list on the Page.

Adding DOM nodes to a page in a short amount of time will obviously make the browser too much, and the results we see are often the browser's stutter or even suspended Animation.

One solution to this problem is the following Timechunk function, where the Timechunk function makes the work of creating nodes in batches, such as creating 1000 nodes in 1 seconds, instead of creating 8 nodes every 200 milliseconds.

    varTimechunk =function(ary,fn,count) {varobj, t; varLen =ary.length; varStart =function(){             for(varI=0;i<math.min (count| | 1,ary.length); i++){                varobj =Ary.shift ();            FN (obj);        }        }; return function() {t= SetInterval (function(){                if(ary.length ===0) {//If all the nodes have been Created.                    returnclearinterval (t);            } Start (); },200);//the time interval for batch execution, which can also be passed in as a parameter        };    }; varary = [];  for(vari=1;i<=1000;i++) {ary.push (i);    }; varRenderfriendlist = Timechunk (ary,function(n) {vardiv = document.createelement (' div '); Div.innerhtml=n;    Document.body.appendChild (div); },8); Renderfriendlist ();

5. Lazy Load function

Because of the differences between browser implementations, Some sniffing work is always unavoidable. Lazy Loading function Scheme.

After entering the conditional branch for the first time, the function is rewritten inside the function, and the function after the rewrite is the addevent function we expect, and the conditional branching statement no longer exists in the Addevent function the next time the Addevent function is Entered.

<body> <div id= "div1" > Click I bind Events </div></body>varAddevent =function(elem,type,handler) {if(window.addeventlistener) {addevent=function(elem,type,handler) {elem.addeventlistener (type,handler,false); }        }Else if(window.attachevent) {addevent=function(elem,type,handler) {elem.attachevent (' On ' +type,handler);    }} addevent (elem,type,handler);    }; vardiv = document.getElementById (' div1 '); Addevent (div,' Click ',function() {alert (1);    }); Addevent (div,' Click ',function() {alert (2); });</script>

JavaScript Design Patterns and development practices-reading notes (3) closures and Higher-order functions

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.