Skip to content

Instantly share code, notes, and snippets.

@elrrrrrrr
Created November 22, 2014 11:35
Show Gist options
  • Select an option

  • Save elrrrrrrr/2c2a87e214647951d7b7 to your computer and use it in GitHub Desktop.

Select an option

Save elrrrrrrr/2c2a87e214647951d7b7 to your computer and use it in GitHub Desktop.
柯里化
//
//简单累加全局变量
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(); // 这里才计算
//提前返回
// 没有使用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