TypeScript var scope与JavaScript var scope

TypeScript var scope versus JavaScript var scope

在这个非常常见的问题上,医生之间遇到了一些有趣的差异。

根据TS文档,使用var声明的变量将从包含函数中泄漏,但在msdn上,它声明var数据不会泄漏,而是可以在包含函数中访问。这可能只是typescript处理var的方式与ecmascript处理var的方式之间的一个差异,希望得到有关这方面的反馈。

根据TS文件

Block-scoping When a variable is declared using let, it uses what some
call lexical-scoping or block-scoping. Unlike variables declared with
var whose scopes leak out to their containing function, block-scoped
variables are not visible outside of their nearest containing block or
for-loop.

但是根据msdn文件

Variables declared by let have their scope in the block for which they
are defined, as well as in any contained sub-blocks. In this way, let
works very much like var. The main difference is that the scope of a
var variable is the entire enclosing function:


这是两种不同的表达方式

医生说(强调我的):

variables declared with var whose scopes leak out to their containing function

这和说什么不同

variables declared with var whose scopes leak out of their containing function


typescript被转换成javascript。当您查看从typescript代码生成的javascript输出时,您将看到使用关键字var声明的变量只是以相同的方式声明的。

所以范围也是一样的:变量在整个包含函数中是可访问的。这有时被称为起重。