this指向

Tutorial: DOM操作 Category: JS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0

this 指向问题

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

  <body>
    <button>点击</button>
    <script>
      // this 指向问题 一般情况下this的最终指向的是那个调用它的对象

      // 1. 全局作用域或者普通函数中this指向全局对象window
      console.log(1, this);

      function fn() {
        console.log("fn: ", this); // Window对象
      }
      window.fn();

      window.setTimeout(function () {
        console.log("setTimeout: ", this); // Window对象
      }, 1000);

      // 2. 方法调用中谁调用this指向谁
      var o = {
        sayHi: function () {
          console.log("o: ", this); // this指向的是 o 这个对象
        },
      };
      o.sayHi();

      var btn = document.querySelector("button");
      // btn.onclick = function () {
      //   console.log(this); // this指向的是btn这个按钮对象
      // };
      btn.addEventListener("click", function () {
        console.log("btn: ", this); // this指向的是btn这个按钮对象
      });

      // 3. 构造函数中this指向构造函数的实例
      function Fun() {
        console.log("Fun: ", this); // this 指向的是fun 实例对象
      }
      var fun = new Fun();
    </script>
  </body>
</html>