javascript中this指向的四种情况

javascript中this指向的四种情况

对象属性中的this指向

  1. 对象属性是函数,则this指向对象本身

  2. 函数内部还有函数,则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指向

  1. 构造函数一级函数中,this指向构造函数new出来的实例

  2. 构造函数二级以上函数,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指向

全局上下文环境中,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或apply后,this指向call或apply方法的参数// 改变调用对象为gObj

// 改变调用对象为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)
posted @ 2020-08-13 14:29  沐雨辰沨  阅读(512)  评论(0编辑  收藏  举报