this指向问题

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>

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值