问题
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
variables.
Scopes of a function in a script without const
or let
variables:
Scopes of a function in a script with a let
variable:
Yet the following prints 1
in the console - variables in the script scope can still be accessed from other scripts:
<script>let v = 1</script>
<script>console.log(v)</script>
I've heard of ES6 modules in which top-level variables won't be accessible from outside a module. Is that what the scope is used for or does it have any another purpose?
回答1:
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>
来源:https://stackoverflow.com/questions/40685277/what-is-the-purpose-of-the-script-scope