一、AOP切片编程
// 我们不希望如下,在原有的goschool中加吃饭功能
function goschool(){
console.log("吃饭");
console.log("上学");
}
// 而是不修改原有功能,去添加新的功能
function eat() {
console.log("吃饭");
}
function goschool() {
console.log("上学");
}
Function.prototype.before = function (cb) {
return () => {
cb();
this();
};
};
const someFn = goschool.before(eat);
someFn();//吃饭,上学
二、函数参数复用
function getTargetStr(region, repoffice) {
return '大屏' + region + repoffice
}
console.log(getTargetStr('中国', '深圳'))
console.log(getTargetStr('中国', '上海'))
// 第一个参数都是中国,那么这个参数是可以复用的,如下
function getTargetStr(region) {
return function(repoffice){
return '大屏' + region + repoffice
}
}
const chinaRegion = getTargetStr('中国')
console.log(chinaRegion('深圳'))
console.log(chinaRegion('上海'))
三、将嵌套执行的函数平铺
function multiply(x) {
return x * 5;
}
function add(x) {
return x + 3;
}
// 嵌套执行就是一个函数的返回值作为另一个函数的参数
const value = multiply(add(2));
// 管道函数实现
function pipe(...fns) {
return function (data) {
return fns.reduce((acc, itemFn) => {
return itemFn(acc);
}, data);
};
}
const value = pipe(add, multiply)(2);
四、防抖
function debounce(fn, delay) {
let timer = null;
return function (...args) {
const firstClick = !timer;
// 防抖
if (timer) {
clearTimeout(timer);
}
// 第一次立即执行操作
if (firstClick) {
// debounce函数renturn出来的函数为任务函数
// 其this指向被绑定的dom,同时帮任务函数的参数传进来
fn.apply(this, args);
}
timer = setTimeout(() => {
// 在delay时间到了之后timer变为null,之前不为null
timer = null;
}, delay);
};
}
function handler(e) {
console.log(this);// 元素
console.log(e);//事件对象
}
const dom = document.getElementById("box");
dom.addEventListener("click", debounce(handler, 2000));
五、节流
function throttle(fn, delay) {
let begin = 0;
return function (...args) {
let cur = new Date().getTime();
if (cur - begin > delay) {
fn.apply(this, args);
begin = cur;
}
};
}
dom.addEventListener("click",throttle(function (e) {
console.log("this", this); // 元素
console.log("e", e); //事件对象
}, 2000)
);