每天一个前端小知识09——this指向问题

总结

  • this指向上一个调用者
  • 箭头函数没有this
  • call, apply, bind可以改变this指向
  • call,apply 改变之后执行一次,bind只改变不执行
  • call传对象,apply传数组

代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>this指向问题</title>
</head>

<body>

</body>

<script>

  // this指向上一个调用者
  console.log(this) // window

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

  let b = {
    
    
    userName: 'beizhen',
    func: function () {
    
    
      console.log(this)
    }
  }
  b.func() // b

  // 字节面试题
  const d = {
    
    
    a: 10,
    b: {
    
    
      a: 20,
      func: function () {
    
    
        console.log(this.a)
      }
    }
  }
  d.b.func() // 20

  // 深信服面试题 箭头函数没有this
  let id = 10
  function x() {
    
    
    setTimeout(() => {
    
    
      console.log(this.id)
    }, 500)
  }
  x({
    
     id: 20 }) // 10
  // call, apply, bind
  // call,apply 改变之后执行一次,bind只改变不执行,call传对象,apply传数组
  x.call({
    
     id: 20 }) //20
</script>

</html>

猜你喜欢

转载自blog.csdn.net/qq_33591873/article/details/128349397