各种函数的this指向问题

        this的指向问题一直是面试的重中之重,深究起来很多人都不能完整地答出this的指向问题。这篇文章将完整地讲述各种函数的this指向问题。下一篇文章介绍了如何通过call、apply、bind来改变this指向,附上入口:改变this指向

建议收藏。前端技术交流Q群:610408494

        this就是“这个、当前”的意思,它的指向一直指向当前函数的运行环境。


  1. 普通函数

        普通函数的this指向调用这个函数的对象,默认是window。严格模式情况下指向undefined。

函数被window调用的话,必定指向window,无论是否是严格模式。

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

    function B() {
        "use strict"
        console.log(this) 
    }
    B();  //undefined
    window.B();  //window

  2. 自执行函数

        自执行函数的this指向window

(function B(){
  console.log(this)  //指向window
})()


  3. 构造函数

        this指向new出来的实例对象,而且优先级是最高的,不能被改变

    function D(name,age) {
        this.name=name
        this.age=age
        this.say=function(word) {
            console.log(this,word)
            //D {name: '刘禅', age: 99, say: ƒ} '本少爷从不坑爹'
        }
    }
    let ls = new D('刘禅',99)
    ls.say('本少爷从不坑爹'); 

4.事件处理函数

        this指向绑定事件的元素

    const eLi =document.querySelector('.eLi')
    eLi.onclick=function(){
        console.log(this)
        // <div class="eLi">按钮</div>
    }

5.箭头函数

  function E(name,age){
        this.name=name
        this.age=age
        this.say=()=>{
            console.log(this)
            // {name: '鲁班七号', age: 99, say: ƒ}
        }
    }
    let lbqh=new E('鲁班七号',99)
    lbqh.say('来打我呀,抓不到我的');

        箭头函数的this指向的是它外面的第一个不是箭头函数的函数的 this, 在定义时就确定了,不能被改变。但是如果想在箭头函数内部访问外部的this,比如Vue框架中比较常用const _this=this、const that = this来定一个新的变量,在箭头函数内部就可以调用外部Vue上的方法和data了。


 
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liuwenjie_

感谢打赏,问题留言~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值