this指向和相关问题

一、this指向
1、普通函数调用,this====>window
function fn(){console.log('11111111')}
fn();//this====>window

2、通过new关键字调用的函数 this===>新创建出来的对象
function Fnn(){this.name='aa';console.log(this)}
var of=new Fnn()//this=====>of

3、通过call,apply,bind调用函数,this--->方法的第一个参数对象
function  fn2(){console.log(this)}
fn2.call(document)//this--->document

4、回调函数,一般this指向window,箭头函数特例
function fn3(fn){fn()}
fn3(function(){
    console.log(this);//this-->window
})

 5、对象内部的方法 this--->当前对象
var obj={
    name:'zz',
    say:function(){
        console.log(this.name)
    }
}
obj.say()//this--->当前对象 obj

6、有箭头函数定义的方法,其内部的this永远指向函数在定义时this关键字的指向单位,与该函数的调用对象无关。
btn1.onclick = function() {
    var count = 0;
    setInterval(()=> {
        count++
    this.innerHTML=count
        console.log(this) //this--->btn
                     
    }, 1000)
             
}

二、this丢失
1、函数嵌套调用,回调函数会导致this指向丢失
解决:将this暂存,然后函数内部用that
btn.οnclick=function(){
    var count=0;
    // 解决办法:将this暂存,然后函数内部用that
    var that=this
    setInterval(function(){
        this
        that
        count++
        console.log(this)//this--->window
        console.log(that)//this--->btn
    },1000)
    fn2.call(this)//通过call保持this指向
    fn3()
    function fn3(){
        console.log(this)//window
    }
    var obj={
        name:this,//this---->btn
        bb:function(){
            console.log(this)//this--->window
        }
    }
    console.log(obj.name)
    obj.bb()
                 
}
function fn2(){
    console.log(this)
}
2、方法赋值,导致this丢失
var obj1={
    fn1:function(){
        console.log(this)
    }
}
obj1.fn1()//this====>obj1
var fn=obj1.fn1///this===>window
fn()

  • 29
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值