函数防抖
n秒内只要你触发事件 就重新计时 事件处理函数的程序将永远不能被执行
fn 需要防抖的函数
time 防抖的事件
triggleNode 是否第一次触发 (布尔值)
function debounce(fn, time, triggleNow) {
var t = null,
res;
var debounced = function () {
var _self = this,
args = arguments;
if (t) {
clearTimeout(t);
}
if (triggleNow) {
var exec = !t;
t = setTimeout(function () {
t = null;
}, time);
if (exec) {
res = fn.apply(_self, args);
}
} else {
t = setTimeout(function () {
res = fn.apply(_self, args);
}, time);
}
return res;
};
debounced.remove = function () {
clearTimeout(t);
t = null;
};
return debounced;
}
函数节流
事件被触发 n秒内只执行一次事件处理函数
fn 要节流的函数
delay 节流的时间
function throttle(fn, delay) {
var t = null,
begin = new Date().getTime();
return function () {
var _self = this,
args = arguments,
cur = new Date().getTime();
clearTimeout(t);
if (cur - begin >= delay) {
fn.apply(_self, args);
begin = cur;
} else {
t = setTimeout(function () {
fn.apply(_self, args);
}, delay);
}
};
}
偏函数
函数的元 -> 参数的个数
有两个参数的函数 -> 二元函数
在计算机科学中 偏函数叫做部分应用 局部应用 指固定一个函数的一些参数 然后产生另一个更小元的函数
函数柯里化与偏函数的区别
函数柯里化是想要一下四种情况 柯里化希望将一个多参数的函数转换成多个单参数的函数 将n元函数转换成n个一元函数
偏函数是先传一部分参数 返回一个新函数最后把参数凑齐 希望固定一个函数的一个或多个参数 将n元函数转换成n-x元的函数
function add(a, b, c) {
return a + b;
}
//函数柯里化
var newFn = curry(add);
newFn(1)(2)(3);//最期望这种形式
newFn(1, 2, 3);
newFn(1, (2, 3));
newFn(1, 2)(3);
//偏函数
var newAdd = partial(add, 1);
newAdd(2, 3);
封装偏函数
Function.prototype.partial = function () {
var _self = this,
_args = [].slice.call(arguments);
return function () {
var newArgs = _args.concat([].slice.call(arguments));
return _self.apply(null, newArgs);
};
};
偏函数案例
Function.prototype.partial = function () {
var _self = this,
_args = [].slice.call(arguments);
return function () {
var newArgs = _args.concat([].slice.call(arguments));
return _self.apply(null, newArgs);
};
};
function formatSentence(time, opt) {
return time + ' ' + opt.user_class + ' ' + opt.name + ':' + opt.sentence;
}
var outPutSentence = formatSentence.partial(
new Date().getHours() + ':' + new Date().getMinutes()
);
console.log(
outPutSentence({
user_class: '骑士',
name: 'james',
sentence: '小皇帝',
})
);

惰性函数
函数内部改变自身
惰性加载表示函数执行的分支只会在函数第一次调用的时候执行 在第一次调用的过程中 该函数被覆盖为另一个按照合适的方式执行的函数 这样任何对原函数的调用就不用再经过执行的分支了
var getTimeStamp = function () {
var timeStamp = new Date().getTime();
console.log(1);
getTimeStamp = function () {
console.log(2);
return timeStamp;
};
return getTimeStamp();
};
console.log(getTimeStamp());
console.log(getTimeStamp());
console.log(getTimeStamp());
console.log(getTimeStamp());
console.log(getTimeStamp());

使用惰性函数封装事件监控函数
function addEvent(el, type, fn, capture) {
if (el.addEventListener) {
addEvent = function (el, type, fn, capture) {
el.addEventListener(type, fn, capture);
};
} else if (el.attachEvent) {
addEvent = function (el, type, fn) {
el.attachEvent('on' + type, function () {
fn.call(el);
});
};
} else {
addEvent = function (el, type, fn) {
el['on' + type] = fn;
};
}
addEvent(el, type, fn, capture);
}
本文含有隐藏内容,请 开通VIP 后查看