JavaScript this的指向

作者: Nian糕 | 来源:发表于2020-06-12 01:00 被阅读0次
    Unsplash

    在 JavaScript 中 this 取什么值,是在函数真正被调用执行的时候确定的,函数定义的时候确定不了,因为 this 的取值是执行上下文环境的一部分,每次调用函数,都会产生一个新的执行上下文环境

    1. this 作为普通函数,指向 window
    function fn1() {
      console.log(this)
    }
    fn1() // window
    
    1. 使用 call() apply() bind(),指向第一个参数
    fn1.call({x: 100}) // 指向第一个参数 {x: 100}
    
    1. 作为对象方法被调用,指向调用该方法的对象
    const niangao = {
      name: '年糕',
      sayHi() {
        // this 即当前对象
        console.log(this)
      },
      wait() {
        setTimeout(function() {
          // this === window
          // setTimeout是作为普通函数去执行,而不是作为niangao.wait()去执行
          console.log(this)
        })
      }
    }
    
    1. class 方法中被调用,指向实例对象
    class Food {
      costructor(name) {
        this.name = name
      }
      eat() {
        console.log(this)
      }
    }
    const niangao = new Food('年糕')
    niangao.eat() // Food{}
    
    1. 箭头函数,指向上级作用域的 this
    const niangao = {
      name: '年糕',
      sayHi() {
        // this 即当前对象
        console.log(this)
      },
      waitAgain() {
        setTimeout(() => {
          // this 即当前对象
          console.log(this)
        })
      }
    }
    
    End of File

    行文过程中出现错误或不妥之处在所难免,希望大家能够给予指正,以免误导更多人,最后,如果你觉得我的文章写的还不错,希望能够点一下喜欢关注,为了我能早日成为简书优秀作者献上一发助攻吧,谢谢!^ ^

    相关文章

      网友评论

        本文标题:JavaScript this的指向

        本文链接:https://www.haomeiwen.com/subject/qsuwtktx.html