JavaScript中关于this指向的4种情况

787 阅读3分钟

对很多前端开发者来说,JavaScript语言的this指向是一个令人头疼的问题。先看下面这道测试题,如果你能实现并解释原因,那本文对你来说价值不大,可以直接略过。

**开篇测试题:**尝试实现注释部分的Javascript代码,可在其他任何地方添加更多代码(如不能实现,说明一下不能实现的原因):

 let Obj = function (msg) {
    this.msg = msg
    this.shout = function () {
      alert(this.msg)
    }
    this.waitAndShout = function () {
      // 隔5秒后执行上面的shout方面
      setTimeout(function () {
        let self = this
        return function () {
          self.shout()
        }
      }.call(this), 5000)
    }
  }

题目的参考答案在文末,但我不建议你直接查看答案,而是先阅读并思考文章的中的知识点。

一、在对象属性中的this指向问题

  • 对象的属性是函数,那么函数中的this指向的是对象本身,即例子中的obj
  var obj = {
    x: 123,
    fn: function () {
      console.log(this) // {x: 123, fn: ƒ}
      console.log(this.x)  // 123
    }
  }
  obj.fn()
  • 对象的属性是函数,函数内部还有函数,那么这个二级(及以上)函数的this指向的是window
 var obj = {
    x: 456,
    fn: function () {
      console.log('fn', this) // {x: 456, fn: ƒ}
      var f1 = function () {
        console.log('fn.f1', this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
        console.log(this.x) // undefined
        var f2 = function () {
          console.log('fn.f2', this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
        }
        f2()
      }
      f1()
    }
  }
  obj.fn()

从上面的例子,我们可以总结出,对象属性中,嵌套超过一级及以上的函数,this指向都是window

二、构造函数中的this指向问题

  • 构造函数中的一级函数,this指向通过构造函数new出来的实例(例子中的person
 var Person = function () {
    this.name = 'linlif'
    this.fn = function () {
      console.log('fn', this) // {name: "linlif", fn: ƒ}
    }
  }
  var person = new Person()
  person.fn()
  • 构造函数中的二级(及以上)函数,this指向的是window
var Person = function () {
    this.name = 'linlif'
    this.fn = function () {
      console.log('fn', this) // {name: "linlif", fn: ƒ}
      var f2 = function () {
        console.log('f2', this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
        var f3 = function () {
          console.log('f3', this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
        }
        f3()
      }
      f2()
    }
  }
  var person = new Person()
  person.fn()

从上面的例子,我们可以总结出,构造函数中,嵌套超过一级及以上的函数,this指向的都是window

三、全局上下文环境中this指向问题

全局上下文环境,this指向浏览器的window对象,例如:

  // 全局的this
  console.log(this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
  console.log(this === window) // true

 // 全局的普通函数
 var global = function () {
    console.log(this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
  }
  global()

四、call()和apply()对this指向的影响

使用call()方法后,this指向call()方法的参数。使用apply()的结果和call()是一致的,这里不做赘述。关于call()apply()用法的区别,请自行查询相关资料。

 // 改变调用对象为gObj
  var gObj = {
    name: 'gName'
  }
  var aaa = function () {
    console.log(this) // {name: "gName"}
    console.log(this.name) // gName
  }
  aaa.call(gObj)
  
  // 改变调用对象为window
  var name = 'global'
  var bbb = function () {
    console.log(this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
    console.log(this.name) // global
  }
  bbb.call(this)

总结:这就是一些关于this的指向问题的个人理解了,如果发现不妥之处,欢迎在评论区指出,或者私信我。

彩蛋 开篇测试题的参考答案,仅供参考!(有意思的地方:题目中,函数名的第一个字母大写,已经暗示这是一个构造函数)

let Obj = function (msg) {
    this.msg = msg
    this.shout = function () {
      alert(this.msg)
    }
    this.waitAndShout = function () {
      // 隔5秒后执行上面的shout方面
      setTimeout(function () {
        let self = this
        return function () {
          self.shout()
        }
      }.call(this), 5000)
    }
  }

  let obj = new Obj('msg')
  obj.waitAndShout()

本篇完。