一、JavaScript惰性函数
function createXHR(){ var xhr = null; try{ //FireFox,Opera 8.0+,Safari,IE7+ xhr = new XMLHttpRequest(); }catch(e){ //Internet Explorer try{ xhr = new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){ try{ xhr = new ActiveXObject("MicroSoft.XMLHTTP"); }catch(e){ xhr = null; } } } return xhr; } //function handleErr(err){ // var errXHR = err; // //} /*惰性函数*/ //第二次生效 function createXHR(){ var xhr = null; if(typeof XMLHttpRequest != ‘undefined‘){ xhr = new XMLHttpRequest(); createXHR = function(){ return new XMLHttpRequest(); } }else{ try{ xhr = new ActiveXObject("Msxml2.XMLHTTP"); createXHR = function(){ return new ActiveXObject("Msxml2.XMLHTTP"); } }catch(e){ try{ xhr = new ActiveXObject("MicroSoft.XMLHTTP"); createXHR = function(){ return new ActiveXObject("MicroSoft.XMLHTTP"); } }catch(e){ createXHR() = function(){ return null; } } } } return xhr; }
二、函数科里化
function curry(fn){ var args = Array.prototype.slice.call(arguments,1); return function(){ var innerArgs = Array.prototype.slice.call(arguments); var finalArgs = args.concat(innerArgs); console.log(finalArgs); return fn.apply(this,finalArgs); } } function add(num1,num2,num3){ return num1+num2+num3; } var t = curry(add,50)(1,2); alert(t);
三、级联函数
function classA(){ this.face = ""; this.mouse = ""; this.leg = ""; } classA.prototype = { setFace: function(){ this.face = "红扑扑"; } setMouse: function(){ this.mouse = "大嘴"; } setLeg: function(){ this.leg = "长腿欧巴"; } }; var person = new classA(); person.setFace(); person.setMouse(); person.setLeg(); console.log(person);
原文地址:http://11317783.blog.51cto.com/11307783/1794399