严格模式 ,原型函数尽量不用箭头
关于Call指向this的说明
const obj = {
uname : 'John'
}
function fn (x,y) {
console.log(this)
console.log(x+y)
}
//调用函数的this用call的方法指向了obj,1和2分别是函数x,y的实参
fn.call(obj,1,2)
apply是用来改变数组的this
//apply求数组最大值
const arr = [23,4,565,76]
const max = Math.max.apply(Math,arr)
console.log(max)
bind方法改变this指向(重点)
const obj = {
uname : 'name',
age : 18
}
function fn () {
console.log(this)
}
//bind不会调用函数,但会改变this
//返回值是函数,但返回值是更改的
const fun = fn.bind(obj)
fun()
-------------------------------------------------------------
document.querySelector('button').addEventListener('click',function () {
//点击后变灰色按钮,this通过原型链一直向上层寻找
this.disabled = true
setTimeout(function() {
this.disabled = false
//this向上寻找到dom获取的btn
}.bind(this),2000)
})
节流函数的一个小例子
const box = document.querySelector('.box')
let i = 0
function mouseM () {
box.innerHTML = i++
}
box.addEventListener('mousemove',stop (mouseM,500))
//节流操作
function stop (fn,time) {
let startTime = 0
return function () {
let now = Date.now()
if (now - startTime >= time) {
fn()
startTime = now
}
}
}
整体思路:先做好事件监听函数的的操作。再设置节流函数,用节流函数的具名函数(形参)填充监听的第二位。设置节流函数带形参并且设置好开始的时间为0,再利用闭包原理返回一个匿名函数设置当前时间,主要的算法就是用现在的时间-设置好的开始时间>=监听事件设置好的时间,再调用节流函数的fn形参,最后一定要重置时间
防抖小案例
const box = document.querySelector('.box')
let i = 1
function move () {
box.innerHTML = i++
}
function de (fn,time) {
let timeID
return function () {
if (timeID) clearInterval(timeID)
timeID = setInterval(function () {
fn()
},time)
}
}
box.addEventListener('mousemove',de (move,200))
通过节流来给视频网站定位进度条
//获取video的方法比较特殊,L0
const video = document.querySelector('video')
//利用lodash来节流,在节流内存放本地视频的播放位置(currentTime)
video.ontimeupdate = _.throttle(()=>{
localStorage.setItem('cur',video.currentTime)
},1000)
//加载视频的位置,取出存放的数据赋值给currentTime
video.onloadeddata = ()=>{
video.currentTime = localStorage.getItem('cur') || 0
}