本文共 1915 字,大约阅读时间需要 6 分钟。
一、JavaScript惰性函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 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; } |
二、函数科里化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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); |
三、级联函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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); |
本文转自yeleven 51CTO博客,原文链接:http://blog.51cto.com/11317783/1794399
转载地址:http://fhpmx.baihongyu.com/