this指向题目
var a ='w'
let obj = {
a:'o',
print:function(){
console.log(this.a)
},
print2:()=>{
console.log(this.a)
}
}
let p = obj.print;
let p2 = obj.print2;
obj.print();
obj.print2();
p();
p2()
owww
p() -->window.p()
p2() --> window.p2()
<button>点击</button>
<script>
var btn = document.querySelector('button');
</script>
//that指向btn
btn.onclick = function(){
var that = this;
setTimeout(function(){
that.disabled = true;
},20)
}
//回调函数里面的this指向了window ,所以这个是不对的
btn.onclick = function(){
setTimeout(function(){
this.disabled = true;
},1000)
}
//箭头函数this为外层的this,也就是调用者btn
btn.onclick = function(){
setTimeout(()=>{
this.disabled = true;
},1000)
}
//用bind绑定this
btn.onclick = function(){
setTimeout(function(){
this.disabled = true;
}.bind(this),1000)
}