一.普通函数this指向
普通函数中this指向调用这个函数的对象
console.log(this,'1'); //window
function fun(){
console.log(this,'2');//window
}
fun()
setTimeout(function(){
console.log(this,'3'); //window
},100)
document.querySelector('button').addEventListener('click',function(){
console.log(this,'4');//button
})
const obj = {
a:function(){
console.log(this,'5');//obj
}
}
obj.a()
严格模式下函数内this指向undefined即'2'对应的输出结果为undefined
二.箭头函数this指向
箭头函数本身没有this,箭头函数的this用的是最近作用域中的this,若没有还会向外层查找
console.log(this,'1'); //window
const fun = ()=>{
console.log(this,'2');//window
}
fun()
setTimeout(()=>{
console.log(this,'3'); //window
},100)
document.querySelector('button').addEventListener('click',()=>{
console.log(this,'4');//window
})
const obj = {
a:()=>{
console.log(this,'5');//window
}
}
obj.a()
三.call
形式: function.call(thisArg, arg1, arg2, ...)
作用: 改变this指向+调用函数
function是要调用的函数。thisArg是要设置为函数执行上下文中的this值的对象。如果传递的值是null或undefined,则会被替换为全局对象。arg1,arg2, ... 是传递给函数的参数列表
const A = {
name:'zs',
age:10
}
function fun(a,b,c){
console.log(this);
console.log(a+b+c);
}
fun(1,2,3)//this指向window
fun.call(A,1,2,3)//改变指向,指向A对象
四.bind
形式: function.bind(thisArg, arg1, arg2, ...)
当调用 function.bind(thisArg, arg1, arg2, ...)时不会立即执行函数,它会返回一个新的函数,这个新函数的this值将永久绑定到thisArg对象上,并在调用时将参数arg1, arg2`, ... 传递给原始函数
const A = {
name:'zs',
age:10
}
function fun(a,b,c){
console.log(this);
console.log(a+b+c);
}
fun(1,2,3)//this指向window
const bindFun = fun.bind(A)//改变this指向,指向A对象
bindFun(1,2,3)
//或者
// const bindFun = fun.bind(A,1,2,3)
//bindFun(1,2,3)()
五.apply
形式: function.apply(thisArg, [argsArray])
接收的第二个参数为一个数组,调用函数+改变this指向
const A = {
name:'zs',
age:10
}
function fun(...args){
console.log(this);
console.log(args);
}
fun(1,2,3)//this指向window
fun.apply(A,[1,2,3])//改变指向,指向A对象
其他。
//点击按钮禁用2秒复原
const btn = document.querySelector('button')
let timer
btn.addEventListener('click',()=>{
clearTimeout(timer)
btn.disabled = true//禁用
timer = setTimeout(()=>{
btn.disabled = false
},2000)
})
这里绑定事件不能用箭头函数,不然this指向window
btn.addEventListener('click',function(){
clearTimeout(timer)
btn.disabled = true
timer = setTimeout(()=>{
this.disabled = false
},2000)
})
btn.addEventListener('click',function(){
clearTimeout(timer)
this.disabled = true//指向btn
timer = setTimeout(()=>{
this.disabled = false//指向btn
},2000)
})
btn.addEventListener('click',function(){
clearTimeout(timer)
this.disabled = true//指向btn
timer = setTimeout(function(){
this.disabled = false//指向window
}.bind(this),2000)//指向外层this的指向即btn
})