手写代码及原理
节流
- 原理: 解决页面频繁计算;定义间隔,不到时间直接返回
1
2
3
4
5
6
7
8
9
10
11function throtter(func, delay) {
let lockFlg = false;
return (...args) => {
if (lockFlg) return;
func(...args);
lockFlg = true;
setTimeout(() => {
lockFlg = false;
}, delay);
};
}防抖
- 原理:解决频繁请求;定义间隔,重复请求清空定时器
1
2
3
4
5
6
7
8
9
10
11
12function debounce(func ,delay, immediately){
let timer = null
return (...args)=>{
clearTimeout(timer)
if(immediately){
func(..args)
}
timer = setTimeout(()=>{
func()
},delay)
}
}柯里化
- 原理: 函数参数收集直到参数收集完成后执行
1
2
3
4
5
6
7
8
9
10function currying(func, ...args) {
let len = func.length;
return (...arg) => {
arg.unshift(...args);
if (arg.length < len) {
return currying(func, ...arg);
}
return func(...arg);
};
}- 原理: 收集参数,不传参数时执行(处理不定参数情况)
1
2
3
4
5
6
7
8function currying1(func, ...args) {
return (...arg) => {
if (arg.length > 0) {
return args.push(...arg);
}
return func(...args);
};
}apply
- 原理:鸭子模型改变调用者
1
2
3
4
5
6function apply(obj = window, args = []) {
obj.fn = this;
const res = obj.fn(...args);
delete obj.fn;
return res;
}bind
- 原理:返回闭包,需处理 new 以及二次绑定
1
2
3
4
5
6
7
8
9function bind(obj = window, args = []) {
const _Fn = this;
return function F(..._args) => {
if(this instanceof F){
return new _Fn(...args, ..._args)
}
return _Fn.apply(obj, args.concat(_args))
};
}call
- 原理:鸭子模型改变调用者
1
2
3
4
5
6function call(obj = window, ...arg) {
obj.fn = this;
const res = obj.fn(...args);
delete obj.fn;
return res;
}jsonp
- 原理: 动态添加 script 标签,定义全局回调
- 回调后删除 节点以及函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22function jsonp(url, data, callBack) {
const dataString = url.indexOf('?') === -1 ? '?' : '&';
const callbackName = `jsonpCB${Date.now()}`;
url += `${dataString}callback=${callbackName}`;
const jsNode = document.createElement('script');
jsNode.url = url;
window[callbackName] = function(result) {
delete window[callbackName];
document.body.removeChild(jsNode);
callBack(result);
};
jsNode.addEventListener(
'error',
() => {
document.body.removeChild(jsNode);
delete window[callbackName];
callBack(result);
},
false
);
document.body.appendChild(jsNode);
}cookie
- cookie 属性
- maxage
- path
- domain
- secure
- cookie 属性
1 | function Cookie() { |