What is the purpose of the script scope?

后端 未结 1 1263
感情败类
感情败类 2021-02-14 10:51

When inspecting scopes of a function in the DevTools console I noticed a \"script\" scope. After a bit of research it seems to be created for let and const

相关标签:
1条回答
  • 2021-02-14 11:41

    When you declare a variable using var on the top level (i.e. not inside a function), it automatically becomes a global variable (so in browser you can access it as a property of window). It's different with variables declared using let and const—they don't become global variables. You can access them in another script tag, but you can't access them as properties of window.

    See this example:

    <script>
      var test1 = 42;
      let test2 = 43;
    </script>
    <script>
      console.log(test1); // 42
      console.log(window.test1); // 42
      console.log(test2); // 43
      console.log(window.test2); // undefined
    </script>

    0 讨论(0)
提交回复
热议问题