JavaScript中 关于this的指向

一、全局中的this

浏览器环境下,this指向window。

console.log(this);//window

二、普通函数中的this

1.严格模式下,普通函数中的this,是undefined。

 'use strict'
       function foo(){
          function bar(){
              console.log(this);//undefined
          }
          bar();
       }
       foo();

2.非严格模式下,全局中的普通函数以及函数内的普通函数,this均指window。

 function foo() {
     function bar() {
          console.log(this);//window
           }
            bar();
        }
    foo();

三、对象中的this

指向的是调用该方法的对象,即对象本身。

let student={
          say(){
               console.log(this);//Object
            }
        }
 student.say();

四、事件方法中的this。

始终指向绑定该事件的事件源。

此处this与event.target区别:event.target指的是触发事件的元素。

<body>
    <div class="box">
        <div class="child"></div>
    </div>
    <button id="btn">按我</button>
    <script>
        document.querySelector(".box").addEventListener('click',function(e){
            console.log('this',this);//box
            console.log('e.target',e.target);//触发元素
        })
        document.querySelector("#btn").addEventListener('click',function(){
            console.log(this); //btn
        })
    </script>
</body>

五、箭头函数中的this。

箭头函数无this,如果要在箭头函数中找this,this指向其所在的父级函数的this。

 let obj = {
             foo() {
                 return () => {
                    console.log(this);//{foo: ƒ}
                }
            }
        }
obj.foo()()

六、构造函数中的this

构造函数中的this,始终指向的是new出来的实例对象。

 function Teacher(name, age, lesson) {
            console.log('teacher', this);//Teacher{ }
            this.name = name;
            this.age = age;
            this.lession = lesson;
   }
       
 let t1 = new Teacher("ann", 23, "JS");

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值