# 代码块
# 继承
function create(o) {
function F() {}
F.prototype = o
return new F()
}
function inherit(child, parent) {
let prototype = create(parent.prototype)
prototype.constructor = child
child.prototype = prototype
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 防抖
N秒后只会执行一次,如果 N 秒内事件再次触发,则会重新计时,例:input输入 参考
function debounce(func, wait, immediate) {
let timer, result
let debounced = function() {
let args = arguments
let context = this
if (timer) {
clearTimeout(timer)
}
if (immediate) {
let callNow = !timer
timer = setTimeout(() => {
timer = null
}, wait);
if (callNow) {
func.apply(context, args)
}
} else {
timer = setTimeout(function() {
func.apply(context, args)
}, wait);
}
}
debounced.cancel = function() {
clearTimeout(timer)
timer = null
}
return debounced
}
let count = 1
let container = document.getElementById('container')
function getUserAction(e) {
container.innerHTML = count++
}
let setUseAction = debounce(getUserAction, 1000, true)
container.onmousemove = setUseAction
document.getElementById("button").addEventListener('click', function(){
setUseAction.cancel();
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 节流
N秒内只执行一次,例:滑动页面
function throttle(func, wait) {
let timer
return function() {
let arg = arguments
let context = this
if (timer) {
return
}
timer = setTimeout(function() {
func.apply(context, arg)
timer = null
}, wait)
}
}
function throttle2(func, wait) {
let previous = 0
return function() {
let arg = arguments
let context = this
let now = +new Date()
if (now - previous > wait) {
previous = now
func.apply(context, arg)
}
}
}
const container = document.getElementById('container')
container.onmousemove = throttle2(function() {
console.log(11111)
}, 3000)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 柯里化
只传递给函数一部分参数来调用它,让它返回一个函数去处理剩下的参数
function currying(fn, ...args) {
if (args.length >= fn.length) {
return fn(...args)
}
return function(...args2) {
return currying(fn, ...args, ...args2)
}
}
function add(x, y) {
return x + y
}
const increment = currying(add, 1)
const a = increment(2)
console.log(a)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# lazyLoad
const imgs = document.getElementsByTagName('img')
const viewHeight = window.innerHeight || document.documentElement.clientHeight
let num = 0
function lazyload() {
for (let i = num; i< imgs.length; i++) {
let distance = viewHeight - imgs[i].getBoundingClientRect().top
if (distance >= 0) {
imgs[i].src = imgs[i].getAttribute('data-src')
num = i + 1
}
}
}
window.addEventListener('scroll', lazyload, false)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15