this关键字

this关键字

函数中的this,this的指向与定义和执行位置没有关系,只关注函数执行前面是否有“.”,有的话则指向“.”前面的对象,如果有多个“.”,指向最近的那个点前面的对象(上一级对象),没有的话指向window,严格模式是undefined

  • 自执行函数执行,this用于指向window(严格模式下undefined)
  • 普通函数执行,函数前面有’.’指向’.’前面的对象,如没有则指向window(严格模式下undefined)
  • 给元素的一个行为事件绑定方法,行为执行时,该方法的this指向该元素
  • 构造函数中this,在创建实例时候指向实例本身
  • call/apply/bind,this指向参数对象(优先级最高,上面4中与第5种同时存在时,以第5个为准)

实战
    // 一
    var b={
      x:12,
     func:function(){}
    }
    window.b.func() // this指向上一级对象b
    var c=b.func;
    window.c() // this指向上一级对象window
    // 二
     var obj=document.getElementById('div1');
     obj.onclick=function(){
       console.log(this); //this->该元素
     }
     function fn(){
       console.log(this);
     }
     obj.onclick=fn;//this ->元素
     obj.onclick=function(){
       //this->元素
       fn() //this ->window
     }
    // 三
     !function(){
       console.log(this)
     }()
    // 四
     function fn(){
           console.log(this);
     }
     var obj={fn:fn};
     fn(); //this->window
     obj.fn()//this->obj 
     function sum(){
       fn();// this -> window
     }
     sum()
     var oo={
       sum:function(){
          console.log(this) //this->oo
           fn() // this->window;
       }
     }
     oo.sum();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值