浅谈对this的理解

"this" 是个关键词,是个存放指针的变量。

前提是在js中,别的语言我更不清楚了:

1、 this 默认指向 是   window

       e.g  

var name ='mongo';
console.log(this.name)       //  mongo
console.log(this)           // window

2、如果给元素添加了事件,当元素调用事件函数的时候, this 指向了 该 元素

       e.g

var oBtn = document.getElementById('btn');

oBtn.onclick = function(){
      console.log(this)      //  oBtn 这个对象元素
}

3、如果给元素添加了事件,而该事件函数里面又套了一层函数, 此时该元素调用 事件函数的时候, this 指向又发生了 变化, 指向了全局 window

      e.g

var oBtn = document.getElementById('btn');

oBtn.onclick = function(){
       setTimeout(function(){
               console.log(this) // window
        },1000)
}
       如果不包一层setTimeout,还可以加 return

       e.g

var oBtn = document.getElementById('btn');

oBtn.onclick = function(){
       return function(){
                console.log(this)   // window
        }
}


4、当遇到new 的时候, this 指向 了一个新的实例对象

       e.g

   

function Person(name){
      this.name = name;
      this.sayName = function(){
              console.log(this.name)
              console.log(this)
       }
}

var onePerson = new Person('mongo')
onePerson.sayName();    // ‘mongo’  onePerson实例对象
5、即便new 很厉害,但是遇到 call 或者apply 也认怂了! 此时的 this  会指向  call或者apply 里面的第一个参数对象!

       e.g

var name = ‘mongo’;

function Person(name){
       this.name = name;
       this.sayName = function(){
               console.log(this.name)
               console.log(this)
        }
}

var onePerson = new Person('liulian');
onePerson.sayName().call('window')   // mongo  此时的this就指向了 全局window

稍稍总结一下, this 是一个存指针的变量, this指向一直在变化, 为什么会变化,应该是随着上下文执行的环境变化而变化吧!  情况大概分为四种:

1、 谁调用了此函数, 那么this 就指向谁

2、如果遇到函数里面又包了一层函数,那么 this的指向就变成全局的了

3、 如果遇到new  那么指向就是 新创建的实例对象

4、如果遇到call 或apply,那么 this 指向就是 call或apply 里面的第一个参数

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值