-
-
Save elrrrrrrr/2c2a87e214647951d7b7 to your computer and use it in GitHub Desktop.
柯里化
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| //简单累加全局变量 | |
| var fishWeight = 0; | |
| var addWeight = function(weight) { | |
| fishWeight += weight; | |
| }; | |
| addWeight(2.3); | |
| addWeight(6.5); | |
| addWeight(1.2); | |
| addWeight(2.5); | |
| console.log(fishWeight); // 12.5 | |
| // | |
| var curryWeight = function(fn) { | |
| var _fishWeight = []; | |
| return function() { | |
| if (arguments.length === 0) { | |
| return fn.apply(null, _fishWeight); | |
| } else { | |
| _fishWeight = _fishWeight.concat([].slice.call(arguments)); | |
| } | |
| } | |
| }; | |
| var fishWeight = 0; | |
| var addWeight = curryWeight(function() { | |
| var i=0; len = arguments.length; | |
| for (i; i<len; i+=1) { | |
| fishWeight += arguments[i]; | |
| } | |
| }); | |
| addWeight(2.3); | |
| addWeight(6.5); | |
| addWeight(1.2); | |
| addWeight(2.5); | |
| addWeight(); // 这里才计算 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //提前返回 | |
| // 没有使用curring | |
| var addEvent = function(el, type, fn, capture) { | |
| if (window.addEventListener) { | |
| el.addEventListener(type, function(e) { | |
| fn.call(el, e); | |
| }, capture); | |
| } else if (window.attachEvent) { | |
| el.attachEvent("on" + type, function(e) { | |
| fn.call(el, e); | |
| }); | |
| } | |
| }; | |
| //curring | |
| var addEvent = (function(){ | |
| if (window.addEventListener) { | |
| return function(el, sType, fn, capture) { | |
| el.addEventListener(sType, function(e) { | |
| fn.call(el, e); | |
| }, (capture)); | |
| }; | |
| } else if (window.attachEvent) { | |
| return function(el, sType, fn, capture) { | |
| el.attachEvent("on" + sType, function(e) { | |
| fn.call(el, e); | |
| }); | |
| }; | |
| } | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment