防抖与节流函数是一种最常用的 高频触发优化方式,能对性能有较大的帮助。
- 防抖 (debounce): 将多次高频操作优化为只在最后一次执行,通常使用的场景是:用户输入,只需再输入完成后做一次输入校验即可。
- function debounce(fn, wait, immediate) {
- let timer = null
-
- return function() {
- let args = arguments
- let context = this
-
- if (immediate && !timer) {
- fn.apply(context, args)
- }
-
- if (timer) clearTimeout(timer)
- timer = setTimeout(() => {
- fn.apply(context, args)
- }, wait)
- }
- }
- 节流(throttle): 每隔一段时间后执行一次,也就是降低频率,将高频操作优化成低频操作,通常使用场景: 滚动条事件 或者 resize 事件,通常每隔 100~500 ms执行一次即可。
- function throttle(fn, wait, immediate) {
- let timer = null
- let callNow = true
-
- return function() {
- let context = this,
- args = arguments
-
- if (callNow) {
- fn.apply(context, args)
- callNow = false
- }
-
- if (!timer) {
- timer = setTimeout(() => {
- fn.apply(context, args)
- timer = null
- }, wait)
- }
- }
- }
16. 函数执行改变this
由于 JS 的设计原理: 在函数中,可以引用运行环境中的变量。因此就需要一个机制来让我们可以在函数体内部获取当前的运行环境,这便是this 。
因此要明白 this 指向,其实就是要搞清楚 函数的运行环境,说人话就是,谁调用了函数。例如:
obj.fn() ,便是 obj 调用了函数,既函数中的 this === obj
fn() ,这里可以看成 window.fn() ,因此 this === window
但这种机制并不完全能满足我们的业务需求,因此提供了三种方式可以手动修改 this 的指向:
call: fn.call(target, 1, 2)
apply: fn.apply(target, [1, 2])
bind: fn.bind(target)(1,2)
17. ES6/ES7
由于 Babel 的强大和普及,现在 ES6/ES7 基本上已经是现代化开发的必备了。通过新的语法糖,能让代码整体更为简洁和易读。
|