函数节流防抖
函数节流(throttle) 、函数防抖(debounce)就是为了去解决用户频繁触发事件的行为。
函数节流
函数节流预定一个函数只在一定周期内只执行一次。
// 函数节流封装
function throttle(handler, wait) {
var lastTime = 0;
return function A() {
var nowTime = +new Date();
// 当前时间 - 上一次点击的时间 >= 1000
if (nowTime - lastTime >= wait) {
// 执行功能
// oDiv.innerHTML = parseInt(oDiv.innerHTML) + 1;
handler()
lastTime = nowTime;
}
}
}
// throttle一定会执行
document.getElementById('btn').onclick = throttle(buy, 1000);
// 抢购功能
function buy() {
oDiv.innerHTML = parseInt(oDiv.innerHTML) + 1;
}
函数防抖
函数防抖在一定的周期内无论触发任意次 ,都只触发最后一次
// 封装函数防抖
function debounce(handle, delay) {
// 请实现功能
var timer = null;
return function A() {
// 1.清除上一次的点击
clearTimeout(timer);
// 2.保存当前的this
var that = this;
timer = setTimeout(function () {
// 改变handle的this指向为that
// handle()
handle.call(that);
}, delay)
}
}
// debounce() - 返回为function A
oIpt.oninput = debounce(ajax, 1000);
// 结果
// oIpt.oninput = function A(){}
console.log(oIpt.oninput);
// var a = 1+2
function ajax() {
console.log(this.value);
}
柯里化
在数学和计算机的角度,柯里化是将一种使用多个参数的函数转换为一次使用一个参数去调用
function add(a, b, c, d) {
return a + b + c + d;
}
// 实现一个柯里化函数Curry
var newAdd = Curry(add);
newAdd(1)(2)(3)(4);
newAdd(1, 2)(3, 4);
newAdd(1, 2, 3)(4);
// add(1,2,3,1)
// add(1,2,3,2)
var n1 = newAdd(1, 2, 3);
n1(1);
n1(2);
n1(3);
function add(a, b, c, d) {
return a + b + c + d;
}
function fixedCurry(fn) {
// 获取到add需要的第一个参数
// var arg = arguments[1];
var arg = [].slice.call(arguments, 1)
console.log(arg);
//
return function () {
// 其他剩余参数做拼接 concat()
// var _arg = Array.from(arguments);
// _arg.unshift(arg);
// Array.from(arguments);
var _arg = arg.concat([].slice.call(arguments));
// apply(this,[])
return fn.apply(this, _arg);
}
}
// var newAdd = fixedCurry(add, 1, 2);
// console.log(newAdd(3, 4));
function Curry(fn, length) {
// 获取剩余参数的个数
var length = length || fn.length;
return function () {
// 1. 如果当前需要的参数已经全部传完
// 判断实参个数 === 形参个数
if (arguments.length === length) {
return fn.apply(this, arguments);
} else if (arguments.length < length) {
console.log(123)
var arg = [fn].concat([].slice.call(arguments));
console.log(arg);
return Curry(fixedCurry.apply(this, arg), length - arguments.length);
}
}
}
var newAdd = Curry(add);
console.log(newAdd(1)(2)(3)(4))
为什么要使用科理化,简化代码结构,提高系统的维护性,一个方法,只要一个参数,强制了功能的单一性,降低代码的重复