this的指向问题


    1、script  全局环境下      this指向window

  console.log(this)//window

    2、函数直接调用    this代表window ,函数内部开启严格模式, this   指向  undefined
    ' use strict'    开启严格模式

function f(){
  
    console.log(this)
   
}
f()//window

开启严格模式

 

function f(){
    //严格模式
     'use strict'
    console.log(this)
   
}
f()//undefined
//开启严格模式 this指向undefined

    3、事件的回调函数中    this------>事件源

document.querySelector('button').addEventListener('click', function () {
        console.log(this)
      })//

    4、构造函数的this  -------->创建出来的对象(new出来的实例化对象)

function Student() {
        this.name = 'zs'
      }

      const s1 = new Student()
      console.log(s1)//Student

    5、定时器    this------->window

setInterval(function () {
        console.log(this) // window
     })

    6、立即执行函数(IIFE)  this------>window


;(function () {
        console.log(this)//Window
      })()

    7、谁调用函数,this就是谁

let obj = {
        a: 10,
        f: function () {
          let a = 100
          console.log(this.a)
        },
      }

      obj.f()//a

你可能感兴趣的:(js常见问题,javascript,前端,开发语言)