脚本作用域的目的是什么? [英] What is the purpose of the script scope?

查看:92
本文介绍了脚本作用域的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在DevTools控制台中检查函数的作用域时,我注意到脚本作用域。经过一些研究,它似乎是为 let const 变量创建的。

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.

不含 const let 变量的脚本中函数的作用域:

Scopes of a function in a script without const or let variables:

具有<$ c $的脚本中函数的范围c> let 变量:

但是在控制台中显示以下 1 -脚本作用域中的变量仍然可以从其他脚本访问:

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>

我听说过ES6模块,其中顶层变量不能从外部访问模块。那是作用域的用途还是它有其他用途?

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?

推荐答案

使用<$ c声明变量时$ c> var 在顶层(即不在函数内部),它将自动成为全局变量(因此在浏览器中,您可以将其作为 window的属性来访问)。使用 let const 声明的变量不同,它们不会成为全局变量。您可以在另一个脚本标签中访问它们,但不能将它们作为窗口的属性来访问。

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.

请参见此示例:

<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>

这篇关于脚本作用域的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆