JS中this指向

本文详细解释了JavaScript中this关键字的指向规则,包括普通函数、箭头函数、DOM事件处理程序中的this行为,以及在严格模式下的变化。同时提到了改变this指向的方法,如call(),apply(),bind()。
摘要由CSDN通过智能技术生成

⛳什么是this

⛳this指向

普通函数的this指向

谁调用就指向谁!!!

来看一些具体的例子👇👇👇

  console.log(this)   //window

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

  setTimeout(function () {
    console.log(this)  //window
  }, 1000)

 congsole.log()、函数调用fn()、setTimeout的完整写法👇👇👇

  window.console.log(this) //window

  function fn() {
    console.log(this) //window
  }
  window.fn()
  
  window.setTimeout(function () {
    console.log(this) //window
  }, 10000)

由此可见他们都是由window调用,所以this都指向window

其他:

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

  const Class = {
    name: 'One',
    sayHi: function () {
      console.log(this)  
    },
    Student: {
      name: '小铃',
      sayHi: function () {
        console.log(this)  
      },
    }
  }
  Class.sayHi() //Class对象
  Class.Student.sayHi() //Student对象 this指向被调用的最近的对象

注意:在严格模式下没有明确写明调用者时,this的值为undefined

  // 严格模式
  'use strict'
  function fn() {
    console.log(this); 
  }
  fn()  //undefined
  window.fn()  //window

箭头函数的this指向

实际箭头函数中不存在this!!!它绑定最近一层作用域中的this

 具体案例👇👇👇

函数调用:

  const fn = () => {
    console.log(this)
  }
  fn()  //window

箭头函数不存在this,往上一层作用域查找即全局作用域,那么此时this指向window对象

DOM节点绑定事件:

  // 箭头函数,此时 this 指向 window
  document.querySelector('button').addEventListener('click', () => {
    console.log(this) // window
  })

  // 普通函数 this指向 button对象
  document.querySelector('button').addEventListener('click', function () {
    console.log(this) // window
  })

原本this指向button按钮对象,当在箭头函数中,箭头函数不存在this,那么往上一层作用域this就指向了window对象

继续👇👇👇

  const Class = {
    name: 'One',
    sayHi: () => {
      console.log(this)
    },
    Student: {
      name: '小铃',
      sayHi: () => {
        console.log(this)
      },
    }
  }
  Class.sayHi()  //window
  Class.Student.sayHi()  //window 

sayHi()为箭头函数不存在this,往上一层作用域即对象,对象内没有this再往外一层层找,找到最外一层即全局作用域,此时this指向window对象

注意


 在了解this在不同场景的默认值后,关于如何改变this的指向可以看我的另一篇博客

JS中改变this的指向:call()、apply()、bind()-CSDN博客

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值