严格模式:
详细见MDN。下面我说几个比较常用的严格情况:
箭头函数的this:
由于箭头函数会指向其调用者的上级,所以一般不在箭头函数中使用this。
那么有没有办法改变this指向呢?
改变this的方法合集:
<button class="btn">获取验证码</button>
<script>
// console.log(this)
// let timer=window.setInterval(function (){
// console.log(this)
// clearInterval(timer)
// },1000)
let arr1=[1,2,3,4,5]
function print(...args) {
this.forEach(function (item,index,o) {
console.log(item)
})
console.log(`others: ${args}`)
}
//1.call方法,修改函数this指向,其中第一个参数是this指向的元素,剩下的会作为参数传递给函数
print.call(arr1,11,22,33,44)
//2.apply方法,修改函数this指向,其中第一个参数是this指向的元素,剩下的必须以数组传递给函数
let arr2=[11,22,33,44]
print.apply(arr1,arr2)
//这里使用到了apply方法
console.log(Math.max(1,2,3,4,5))//正常情况我们不能传递数组进入
console.log(Math.max.apply(null,arr2))//这是转变this的方法,因apply必穿数组类型数据
console.log(Math.max(...arr2))//使用...扩展运算符解开数组
//3.bind方法,修改函数this指向,其中第一个参数是this指向的元素,剩下的会作为参数传递给函数
//call和apply都会直接调用函数,而bind方法可以转换this后再使用表达式函数的变量来调用
let newPrint=print.bind(arr1,3,4,4,3)
newPrint()
//如果想直接调用可以使用()直接加在修改后的后面
print.bind(arr1,5,6,7,{a:1})()
//下面给出实例
let getBtn=document.querySelector('.btn')
getBtn.addEventListener('click',function () {
this.disabled=true
window.setTimeout(function () {
this.disabled=false
}.bind(this),2000)
})
</script>
这一部分很重要请详细查看。