JavaScript design pattern and open practice Learning (III.) application of higher order function

Source: Internet
Author: User

First, AOP (aspect-oriented programming)

Function.prototype.before=function(beforefn) {var_self= This;//keep a reference to the original function        return function() {//returns the "proxy" function that contains the original function and the new functionBeforefn.apply ( This, arguments);//execute new function, fix this            return_self.apply ( This, arguments);//executing the original function}} Function.prototype.after=function(AFTERFN) {var_self= This; return function () {            varRet=_self.apply ( This, arguments); Afterfn.apply ( This, arguments); returnret; }    }    varFunc=function() {Console.log (2); } func=func.before (function() {Console.log (1); }). After (function() {Console.log (3)    }); Func ();

Second, currying function currying

Currying is also called partial evaluation. The value is not evaluated in the process and is evaluated in the last step.

Such as:

 varcurring=function(FN) {varargs=[]; return function () {            if(arguments.length==0){                returnFn.apply ( This, args); }Else{[].push.apply (args,arguments); returnArguments.callee//returns the Function object that is being executed            }        }    }    varCost= (function () {        varMoney=0; return function () {             for(vari=0,l=arguments.length;i<l;i++) { money+=Arguments[i]; }            returnMoney ;    }    })(); varCost=curring (cost);//Convert to curring functionCost (100); Cost (200); Cost (300); Console.log (Cost ())

Output 600, in the first 3 function calls to keep the values in the array, the last step of the array summation.

Third, uncurring

One object borrows a method or property that leads another object

Uncurring the Array.prototype.push of the

function.prototype.uncurrying=function () {        varself= This; return function () {            varObj=array.prototype.shift.call (arguments);//Remove the first value of arguments and remove the first value from a arguments            returnself.apply (obj,arguments);    };    }; varPush=Array.prototype.push.uncurrying (); (function() {push (arguments,4); Console.log (arguments);//output [1,2,3,4]})

And so on, other array methods can also be uncurring

function.prototype.uncurrying=function () {        varself= This; return function () {            varObj=array.prototype.shift.call (arguments);//Remove the first value of arguments and remove the first value from a arguments            returnself.apply (obj,arguments);    };    };  for(vari=0,fn,ary=[' push ', ' shift ', ' ForEach '];fn=ary[i++];) {ARRAY[FN]=array.prototype[fn].uncurrying ();    }; varobj={        "Length": 3,        "0": 1,        "1": 2,        "2": 3    }; Array.push (obj,4); Console.log (obj.length);//Output 4    varfist=array.shift (obj); Console.log (fist);//Output 1Console.log (obj);//output {0:2.1:3,2:4,length:3}Array.foreach (obj,function(i,n) {console.log (n);//Output 0,1,2 separately})

Four, function throttling

Resolve frequent call issues

varthrottle=function(fn,interval) {var_SELF=FN,//Save a function reference that needs to be deferredTimer//TimerFisrttime=true;//whether to call the first time        return function () {            varargs=arguments, _me= This; if(Fisrttime) {//if it is the first load, no delay is required_self.apply (_me,args); returnFisrttime=false; }            if(timer) {//If the timer is still there, it indicates that the previous delay was not completed.                return false; } Timer=settimeout (function() {cleartimeout (timer); Timer=NULL;            _self.apply (_me,args); },interval|| 500);//|| Determine if the interval is set, if the initial value is not given        };    }; Window.onresize=throttle (function() {Console.log (1); },500);

Five, time-sharing function

Prevents excessive loading at one time, making tick calls.

 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)//time interval for batch execution        }    }    varary=[];  for(vari=1;i<=1000;i++) {Ary.push (i);//let's say ary loaded 1000 friends    }    varRenderfriendlist=timechunk (ary,function(n) {varDiv=document.createelement (' div '); Div.innerhtml=N;    Document.body.appendChild (DIV); },8); Renderfriendlist ();

Vi. Lazy Load function

The first time you go to a branch, you override the function, and the second is not branching.

 varAddevent=function(elem,type,handler) {if(Window.addeventlistener) {//Non-IEAddevent=function(Elem,type,handler) {Elem.addeventlistener (Type,handler,false); }        }        Else if(window.attachevent) {//non-standard, only support IEAddevent=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); });

JavaScript design pattern and open practice Learning (III.) application of higher order function

Related Article

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.