1.闭包
概念:一个函数加上创建函数的作用域的连接,关闭了函数的自由变量(及内部函数可以访问外部函数的变量) | 在一个内部函数中,对外部作用域的变量进行引用,
优点: 1.可以避免使用全局变量,防止全局变量污染;
缺点:1. 变量会贮存在内存中。造成内存损耗
2. Ie浏览器可能造成内存泄露
常用:1.循环组件添加触发事件 。2.防抖、节流
2.防抖
常用:搜索框联想等功能
//定时器版
function debounce(fun,time){
var timer = null;
return function () {
if (timer){
clearTimeout(thisTime)
}
timer = setTimeout(fun,time);
}
}
3.节流
常用:封装组件设定loading,禁用等
//定时器版
const throttle = (func, limit) => {
let inThrottle; // 是否处于节流限制时间内
return function() {
if (!inThrottle) {
const context = this; //将指向window的this保存
const args = arguments;
func.apply(context, args); // 执行回调,并且this指向window
inThrottle = true;
// 开启定时器计时
setTimeout(() => inThrottle = false, limit);
}
}
}
//时间戳版,第一次不触发
const throttle = (func, limit) => {
let old=Date.now();
return function() {
if (Date.now()-old>=limit) {
const context = this; //将指向window的this保存
const args = arguments;
func.apply(context, args); // 执行回调,并且this指向window
old=Date.now()
}
}
}
4.在vue项目中怎么使用防抖节流函数
<el-button id="btn" @click="add">添加</el-button>
常见错误:直接调用
原因:这个和vue的事件绑定原理有关。如果直接在函数体内部使用的话,结果就是是,一个匿名的立即执行函数来进行执行。由于每次触发点击事件都会返回一个新的匿名函数, 就会生成一个新的函数执行期上下文(称之为执行栈),所以就会防抖/节流就会失效
具体可看:详细参考
import { throttle } from "@/utils/tools.js"
export default {
methods: {
// 这种用法是不生效的
add () {
throttle(fun2, 2000)
},
fun2 () {
console.log("执行函数")
}
}
}
正确写法:
* 关于this指向域问题,这里匿名函数this的指向就是undefined了。
解决方法1:不再建议使用箭头函数,这样通过vue实例调用该方法,this就可以指向vue实例了。
import { throttle } from "@/utils/tools.js"
export default {
data(){
return{
title:"data里面内容"
}
},
methods: {
add:throttle(function(){
//这里不建议再使用箭头函数了,
console.log("访问data内容",this.title)
},2000)
}
}
解决方法2:先将this存下来,后面就可以在箭头函数里用了
import { throttle } from "@/utils/tools.js"
let that = null
export default {
data(){
return{
title:"data里面内容"
}
},
created(){
that = this
},
methods: {
add:throttle(()=>{
console.log("访问data内容",that.title)
},2000)
}
}