目录
1. 参数复用
function uri(protocol, hostname, pathname) {
return `${protocol}${hostname}${pathname}`;
}
const uri1 = uri('https://', 'www.123.com', 'dir');
console.log(uri1);
如果我们有很多类似的内容,会导致非常多重复的参数, 因此我们需要进行参数复用 这里再创建一个函数
function uri_curring(protocol) {
return function (hostname, pathname) {
return `${protocol}${hostname}${pathname}`;
}
}
const uri_https = uri_curring('https://');
console.log(uri_https);
这里可以看到uri_https 是一个函数因为作用域链的关系,这里返回的函数是可以使用外部这个参数的,因此我们再来新增三个变量,这样可以大大减少代码量
function uri_curring(protocol) {
return function (hostname, pathname) {
return `${protocol}${hostname}${pathname}`;
}
}
const uri_https = uri_curring('https://');
const uri1 = uri_https('www.baidu.com','dir')
const uri2= uri_https('www.souhu.com', 'dir')
const uri3 = uri_https('www.123.com', 'dir')
console.log(uri1,uri2,uri3);
2.兼容性的检测
需要判断代码与浏览器是否兼容,经常要判断的就是事件监听了,addEventListner(主流浏览器的方法)和attachEvent(IE的方法)不管在实际应用还是面试中都会碰到
const whichEvent=(function () {
if(window.addEventListener){
return function (element,type,listener,useCapture) {
element.addEventListener(type,function (e) {
listener.call(element,e);
},useCapture)
}
} else if (window.attachEvent){
return function (element, type, handler) {
element.attachEvent('on'+type,function (e) {
handler.call(element, e);
})
}
}
})();
element:哪个元素需要添加事件监听,type:元素需要添加什么类型的事件
listener:执行的回调函数 useCapture:进行事件冒泡或者事件捕获的选择
为了规避掉this指向的问题这里用call进行this的绑定
只需要用一个函数就可以实现不同兼容性的功能而且因为立即执行函数的原因,触发多次事件也依旧只会触发一次if条件判断
3.延迟执行
在某些情况下,对参数复用功能进行改进 add(1)(2)(3)=6
add(1,2,3)(4)=10 add(1)(2)(3)(4)(5)=15
执行第一个括号的时候返回inner函数 执行第二个括号的时候返回inner函数....不断地自己调用自己
function add() {
let args = Array.prototype.slice.call(arguments)// let args=arguments; 把对象转化为数组
let inner = function () {
args.push(...arguments);//“...”是展开运算符
return inner;
//函数被转换为字符串显示了 调用内部toString方法 发生隐式转换
// let sum=args.reduce(function (pre,cur) {
// return pre+cur;
// })
// return sum;
}
inner.toString = function () {
return args.reduce(function (pre, cur) {
return pre + cur;
});
}
return inner;
}
const result = add(1)(2)(3)(4);//10
console.log(result);//是函数类型
4.柯里化技术的箭头函数
const list1 = [
{ mid: '甄姬', profession: '法师' },
{ mid: '妲己', profession: '法师' },
{ mid: '小乔', profession: '法师' }
]
const list2 = [
{ mid: '橘右京', profession: '打野' },
{ mid: '镜', profession: '打野' },
{ mid: '赵云', profession: '打野' }
]
// console.log(list1.map(hero => hero.mid));
// console.log(list2.map(hero => hero.profession));
const curring = names => element => element[names];
const name_mid = curring('mid');
const name_pro = curring('profession')
console.log(list1.map(name_mid));
console.log(list2.map(name_pro));