js中this为什么有时会指向undefined

68 阅读1分钟

总结:

1、普通函数中的this,谁调用就指向谁。但是在严格模式下,原本指向window的this此时会指向undefined。

2、箭头函数中的this,是由定义时所处的上下文决定的。

3、有个例外:即使是严格模式下,setTimeout中的延迟执行代码中的this该指向window的还是指向window。

示例:

<!DOCTYPE html>
<html lang="en">
  <body>
    <script>
      function foo1() {
        console.log("foo1", this);
      }
      const foo2 = () => {
        console.log("foo2", this);
      };

      foo1(); // Window
      foo2(); // Window
    </script>

    <script>
      "use strict";
      function foo3() {
        console.log("foo3", this);
      }
      const foo4 = () => {
        console.log("foo4", this);
      };

      foo3(); // undefined
      foo4(); // Window
    </script>

    <script>
      setTimeout(() => {
        console.log("foo5", this); // Window
      }, 0);

      setTimeout(function () {
        console.log("foo6", this); // Window
      }, 5);
    </script>

    <script>
      "use strict";
      setTimeout(() => {
        console.log("foo7", this); // Window
      }, 10);

      setTimeout(function () {
        console.log("foo8", this); // Window
      }, 15);
    </script>
  </body>
</html>