Navigation

    云、贵、川、渝IT人的圈子
    • Register
    • Login
    • Search
    • 主页
    • 问答
    • 话题
    • 热门
    • 圈子
    • 招聘
    • 活动
    • 项目

    this 作用域指向详解

    技术答疑
    1
    1
    28
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • diepao172
      diepao172 last edited by

      this总是代表着他的直接调用者,例如obj.fun(),那么fun()中的this就是obj

      举例

      import axios from 'axios'
      export default new class {
        constructor() {
          this.sayhello()
          // => "hello"
          
          axios.get('xxx.com').then(function() {
            // 此时this指向的是function函数本身,无法获取到父级的方法
            this.sayhello()
            // => sayhello undefined
          })
      
          // 箭头函数修改this作用域
          axios.get('xxx.com').then(() => {
            this.sayhello()
            // => "hello"
          })
      
          // 拷贝this作用域
          var that = this
          axios.get('xxx.com').then(function() {
            that.sayhello()
            // => "hello"
          })
        }
      
        sayhello() {
          console.log('hello')
        }
      }
      
      1 Reply Last reply Reply Quote 0
      • First post
        Last post
      8
      玻
      U
      A
      大
      A
      青
      黑
      低
      天
      白
      快
      爱
      白
      美
      此
      荒
      为
      哭
      柳
      无
      真

      社群
      昆明网页设计交流吧
      友情链接
      • Funtask
      • Funtask 社区
      • SUWIS
      • 云南北大青鸟
      ©2019-2020 滇ICP备20006698号