JavaScript中的this指向问题

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <!--this问题
    1. 当函数作为普通函数调用时,this 在非严格模式下指向全局对象(浏览器中是 window,Node.js 中是 global),在严格模式下则是 undefined,如1-1。
    2. 当函数作为对象的普通函数调用时,this 指向该对象。
    3. 箭头函数不会创建自己的 this,它会捕获其定义位置的 this 值(即词法作用域中的 this)
    4. 在一个对象的方法中定义了一个箭头函数,箭头函数的 this 就是定义这个箭头函数的方法的 this,而不是调用这个箭头函数时的 this。
    5. 当使用 new 关键字调用函数时(构造函数),this 指向新创建的实例对象。
    6. 可以使用 call 或 apply 显式地指定 this 的值。
    -->
    <script type="text/javascript">
      //1、普通函数
      function fun1() {
        console.log("fun1:", this);
      }
      fun1(); //输出window;
      let a1 = fun1(); //输出window;
      console.log(a1); //输出值为fun1中return的值,没有return则为undefined

      const obj = {
        a: 10,
        // 2、对象的方法
        fun2: function () {
          console.log("fun2:", this);
        },
        // 3、对象内的箭头函数
        fun3: () => {
          console.log("fun3:", this);
        },
        // 4、对象的方法中定义的箭头函数
        fun4: function () {
          const way = () => {
            console.log("fun4-way:", this);
          };
          way(); //输出输出 obj对象
        },
      };

      obj.fun2(); // 输出obj对象
      obj.fun3(); // 输出window;
      obj.fun4(); // 输出obj对象,way是在fun4内定义的,所以way的this就是fun4的this,即obj对象

      //5. 构造函数(用new关键字调用的函数)
      function fun5() {
        this.name = "example";
        console.log("fun5:", this);
      }
      const instance = new fun5(); // 输出实例对象fun5

      // 6、 call 和 apply
      function fun6() {
        console.log("fun6:",this);
      }
      const obj2 = { name: "example" };
      fun6(); //为1情况,输出window
      fun6.call(obj2); // 输出 obj2
      fun6.apply(obj2); // 输出 obj2
    </script>
  </body>
</html>
posted @ 2024-08-01 11:49  曾小瓜同学  阅读(7)  评论(0编辑  收藏  举报