让可变范围 [英] let Variable Scope

查看:41
本文介绍了让可变范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将输出"1".但是,关键字"let"是否不应该使x成为全局变量,从而使它对das()不可见?let应该将变量的范围限制为仅声明它们的块,但是在这里,我看到一个内部函数可以访问"let"变量,即使x是在其范围之外声明的.那怎么可能?

The following code will output "1." However, shouldn't the keyword "let" not make x a global variable, thus making it invisible to das()? let is supposed to limit the scope of variables to only the block where they're declared, yet here, I'm seeing an inner function have access to a "let" variable, even though x was declared outside its scope. How is that possible?

function letTest() {
	function das () {
		console.log(x);
// How does this function have access to a let variable declared outside its scope?
	}

	let x = 1;
	das();
}
letTest();

推荐答案

这是一种思考 let 的工作方式的方法:

Here's a way of thinking about how let works:

  1. let 开始.
  2. 在相同的嵌套级别上,遍历/遍历源代码,找到第一个 {.
  3. 现在从 let 中找到相应的} .
  1. Start from the let.
  2. At the same nesting level, working back/up through the source code, find the first {.
  3. Now from the let find the corresponding }.

这为您提供了变量可见的范围.如果函数定义出现在该范围内,则可以;该变量对于该函数中的代码可见.

That gives you the scope wherein the variable will be visible. If a function definition appears in that scope, fine; the variable is visible to code in that function.

现在,有点奇怪,在您的示例中,变量看起来像,它在声明之前的范围中使用.那就是引用出现在声明之前的事实变得更加有趣了.

Now, what's a little bit weird is that in your example the variable looks like it's used in the scope before it's declared. That's where the fact that the reference appears before the declaration becomes a little more interesting.

通常,如果作用域中的代码在 let 实际发生之前引用了 let 声明的变量,那是错误的.但是,那是运行时的事情,而不是语法的事情.在您的情况下,在运行时,调用嵌套函数时 let 会发生".

Normally, if code in a scope refers to a let-declared variable before the let actually happens, that's an error. However, that's a runtime thing, not a syntax thing. In your case, at runtime the let will have "happened" by the time the nested function is called.

这篇关于让可变范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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