this指向

this是一个在作用域内的关键字

指向

全局使用:this -> window

 console.log(this);   // Window

普通调用:this -> window

 function fn() { console.log(this); }  // Window
 fn(); 

对象调用:this -> .前的对象

 function fn() {
   console.log(this);  // {fun: ƒ} 即 obj
 }
 var obj = {
   fun: fn
 }
 obj.fun(); 

定时器处理函数:this -> window

 setTimeout(fn, 0)   // Window
 setTimeout(obj.fun, 0)  // Window

事件处理函数:this -> 事件源

  <div id="btn">this指向</div>
  var btn = document.getElementById('btn');
 btn.onclick = fn;  // dom: <div id="btn">this指向</div>
 btn.onclick = obj.fun;  // dom: <div id="btn">this指向</div>

自执行函数:this -> window

 !function () {console.log(this)} ()  // Window

需要强调的一点是:this指向只看调用方式,例:

    var btn = document.getElementById('btn')
    btn.onclick = function(){
      console.log(this);
      function fn() {
        console.log(this);
      }
      var obj = {
        fun: fn
      }
      fn();
      obj.fun();
    };
    // <div id="btn">this指向</div>
    // Window {window: Window, self: Window, document: document, name: '', location: Location, …}
    // {fun: ƒ}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值