this关键字指向

JavaScript中this的指向解析
本文深入探讨了JavaScript中的this关键字,重点解析其在不同场景下的指向问题,包括函数调用、方法调用、构造函数调用以及箭头函数中的行为。通过实例分析,帮助读者理解this的本质和变化规律。
<!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>Document</title>
</head>

<body>
  <button>按钮</button>
</body>
<script>
  //1、全局环境下的 this => Window
  console.log(this);

  // 2、全局普通函数 this => Window
  function fun() {
    console.log(this);
  }
  fun(); //等同于window.fun();

  // 3、内部函数中的this  this=》Window
  function fun() {
    function sayName() {
      console.log(this); // 方法中谁调用指向谁 所以指向window
    }
    sayName(); //等同于window.sayName() 
  }
  fun();

  // 4、方法中的this指向调用方法的对象 this=》outer
  function outerFun() {
    this.name = '小小';
    this.sayName = function () {
      console.log(this);
    }
  }
  let outer = new outerFun();
  outer.sayName();

  //5、事件中的this,指向触发事件的DOM对象 this=> <button>按钮</button>
  document.querySelector("button").onclick = function () {
    console.log(this);
  }

  // 6 、构造函数中的this指向new创建的对象 this =》 Person
  class Person {
    constructor() {
      console.log(this);
    }
  }
  let person = new Person();

  // 7、箭头函数中的this指向定义函数上下文的this this=》Admin
  function Admin() {
    this.sayName = function () {
      console.log(this);
      setTimeout(() => {
        console.log(this);
      }, 100)
    }
  }
  var admin = new Admin();
  admin.sayName();

  // 8、普通函数中的this指向定义函数上下文的this this=》Window
  function Admin() {
    this.sayName = function () {
      console.log(this);
      setTimeout(function () {
        console.log(this);
      }, 100)
    }
  }
  var admin = new Admin();
  admin.sayName();
</script>

</html>

结果

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值