不同场景下this的取值

文章详细探讨了JavaScript中this的指向规则,包括在普通函数、严格模式、call/apply/bind方法、定时器以及箭头函数中的不同表现。在普通函数中,非严格模式下this指向window,而严格模式下this为undefined。call方法的this取决于调用时传入的对象。定时器中,常规函数内的this指向window,而箭头函数内的this则继承自上层作用域。
摘要由CSDN通过智能技术生成

1.普通函数中

  • 非严格模式下:this -> window
function fn() {
      console.log(this) // window
    }
    fn()
  • 严格模式下:this ->undefined
'use strict'
    function fn() {
      console.log(this) // undefined
    }
    fn()

2.call、apply、bind中

这里以call为例

  • 调用时啥也不传(包括 null、undefined):this -> window
function fn() {
      console.log(this)
    }
    fn.call() // window
    fn.call(null) // window
    fn.call(undefined) // window
  • 传入什么,this就是什么
function fn() {
      console.log(this)
    }
    fn.call(123) // {1,2,3}
    fn.call({ age: 22 }) // {age: 22}

3.定时器中

  • 定时器 + function:this -> window
setTimeout(function () {
      console.log(this) // window
    }, 100)
  • 定时器 + 箭头函数:this -> 上层作用域的this
 class Obj {
      fn(){
        setTimeout(() => {
          console.log(this);
        }, 100);
      }
    }
    let obj1 = new Obj();
    obj1.fn() // Obj 

4. 箭头函数

  • 有 function 作用域:this是上层作用域的this
class Obj {
      fn = () => {
        console.log(this)
      }
    }
    let obj1 = new Obj()
    obj1.fn() // Obj
  • 没有 function 作用域:this -> window
 let obj = {
      fn: () => {
        console.log(this)
      }
    }
    obj.fn() // window

今日寄语:生以悦己,非困于人!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值