this 是指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,一般情况下this的最终指向是调用它的对象
1、全局作用域或者普通函数中this指向窗口顶级对象window(注意定时器里面this指向window)
console.log('全局:',this);
function demo(){
console.log('demo:',this);//window
// 这里的函数 其实也是再全局下调用的 相当于window.demo() 所以打印的结果还是window
}
demo();
window.setTimeout(funtion() {
console.log(this);
},1000)
2、 对象里面的this指向
var person = {
realname:'张三',
age:20,
say:function(){
console.log('说话');
console.log(this);//指向的是当前对象本身 person
}
};
console.log(person.realname);
person.say();
3、构造函数里面的this指向问题
function Person(realname,age){
this.realname = realname;
this.age = age;
this.say = function(){
console.log('说话');
console.log(this);//构造函数里面的this 指向的是实例化的这个对象
// 实例化指的是 new出来的实例
}
}
var p1 = new Person('李四',22);
var p2 = new Person('王武',23);
p1.say();
p2.say();
4、在定时器里面的this指向
var btn= document.querySelector('#btn');
btn.onclick = function(){
console.log(this);//btn对象
setTimeout(function(){
console.log(this);//定时器 是window调用的 所以这里打印的是window
},1000)
}
5、案列中的this指向
<input type="number">
<button>发送</button>
<script>
var btn=document.querySelector('button');
var time=3;
btn.addEventListener('click',function(){
btn.disabled=true;//可以修改成this.disabled=true;其指向的是btn
var timer=setInterval(function(){
if(time==0){
clearInterval(timer);
btn.disabled=false;//不可修改this指向,其函数指向的是定时器函数(即window对象),不是btn对象下的函数
btn.innerHTML='发送'
}else{
btn.innerHTML='还剩下'+time+'秒';
time--;
}
},1000);
})
</script>