注意:
事件回调函数使用箭头函数时,this为全局的window,因此dom事件回调函数如果里面需要用到dom对象的this,不推荐使用箭头函数
const btn = document.querySelector('button');
/*btn.addEventListener('click',function(){
console.log(this);
// this指向btn
})*/
btn.addEventListener('click',()=>{
console.log(this);
// this 指向window
})
基于原型的面向对象也不推荐采用箭头函数
function Person(){}
Person.prototype.play = function(){
console.log(this);
// this 指向Person
}
Person.prototype.walk = ()=>{
console.log(this);
// this 指向window
}
const p1 = new Person();
p1.play();
p1.walk();
使用call方法调用函数,同时指定被调用函数中this的值
function fn(x,y){
console.log(this);
// 指向window
console.log(x,y);
}
fn();
const obj = {
name:'liuze'
}
fn.call(obj,1,2);
// 此时fn里边的this指向obj,1,2相当于实参
fun.apply(thisArg,[argsArray])
thisArg:在fun函数运行时指定的this值
argsArray:传递的值,必须包含在数组里面
返回值就是函数的返回值
function fn(x,y){
console.log(this);
// 指向window
console.log(x,y);
return x+y;
}
fn();
const obj = {
name:'liuze'
}
const res = fn.apply(obj,[1,2]);
// 此时fn函数中的this指向obj
console.log(res);
// 3
不会调用函数,但是能改变函数内部this的指向
fun.bind(thisArg,arg1,arg2,…)
function fn(x,y){
console.log(this);
// 指向window
console.log(x,y);
return x+y;
}
fn();
const obj = {
name:'liuze'
}
const fun2 = fn.bind(obj,1,2);
// 此时fn函数中的this指向obj
console.log(fun2());
单位时间内,频繁触发事件,只执行最后一次
使用场景
搜索框搜索输入,只需用户最后一次输入完,再发送请求。
利用防抖来处理-鼠标划过盒子显示文字
DOCTYPE html>
<html>
<head>
<title>javascripttitle>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.box{
width: 200px;
height: 200px;
background-color: red;
margin: 0 auto;
line-height: 200px;
text-align: center;
}
style>
head>
<body>
<div class="box">1div>
body>
<script type="text/javascript">
const box = document.querySelector('.box');
var i = 1;
box.addEventListener('mousemove',function(){
box.innerHTML = i ++;
})
script>
html>
运行结果:

实现方式:
lodash提供的防抖来处理
const box = document.querySelector('.box');
var i = 1;
function mouseMove(){
box.innerHTML = i ++;
}
box.addEventListener('mousemove',_.debounce(mouseMove,500))
// 1. 利用lodash库实现防抖,500ms之后采取+1
手写一个防抖函数来处理
const box = document.querySelector('.box');
var i = 1;
var timer = null;
box.addEventListener('mousemove',function(){
if(timer != null){
clearTimeout(timer);
}
timer = setTimeout(()=>{
box.innerHTML = i++;
},500);
// 休眠500ms
})
运行结果:

单位时间内,频繁触发事件,只执行一次
实现方式:
利用lodash提供的节流来实现
const box = document.querySelector('.box');
var i = 1;
function mouseMove(){
box.innerHTML = i++;
}
box.addEventListener('mousemove',_.throttle(mouseMove,3000));
手写一个防抖函数来处理
const box = document.querySelector('.box');
var i = 1;
var timer = null;
box.addEventListener('mousemove',function(){
if(!timer){
timer = setTimeout(function(){
box.innerHTML = i++;
timer = null;
},3000);
}
});
运行结果:
