Typescipt 1.5中的“var”和“let” [英] 'var' and 'let' in Typescipt 1.5

查看:153
本文介绍了Typescipt 1.5中的“var”和“let”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Typescript中使用 var 还是 let 有什么不同?我知道'let'允许将变量进一步定义在一个范围内,而不会在该范围之外被使用。这显然是for循环中迭代器的一个很好的优势。我知道这是一个ES6定义,所以编译到ES6应该看起来与'var'和'let'几乎相同。

What exactly is the difference between using either 'var' or 'let' in Typescript? I know that 'let' allows the variable to be defined further into a scope without it being used outside of said scope. That is obviously a nice advantage for iterators in for loops. I know this is an ES6 definition, so compiling to ES6 should look nearly identical in terms of 'var' and 'let'.

但是,当它汇编成不支持let的ES5 javascript时,究竟发生了什么?是否有编译器创建的奇怪命名的变量,以防止在Typescript文件的上下文中使用所述变量?在整个功能中定义许多let变量的情况下会发生什么?是否有性能影响我应该关心?

But, when it compiles down into ES5 javascript which doesn't support 'let', what exactly is happening? Are there oddly named variables that the compiler creates so that it prevents using said variables in the context of the Typescript file? What happens in situations where you define many 'let' variables throughout a function? Is there a performance impact I should be concerned about?

基本上,当typcript编译将变量设置为ES5 javascript时发生什么?

推荐答案

找到这些类型问题的答案的最简单的方法是在 TypeScript Playground

The easiest way to find answers to these type of questions to try it out in the TypeScript Playground.

TypeScript重命名块范围内的变量。与使用 var 定义的常规变量相比,没有性能开销。

TypeScript renames the variables within the block scope. There's no performance overhead compared to using regular variables defined with var.

此代码:

var i = 0;
for (let i = 0; i < 5; i++) {}
i++;

编译为:

var i = 0;
for (var i_1 = 0; i_1 < 5; i_1++) { }
i++;

这里是关于 let 的更多信息。

这篇关于Typescipt 1.5中的“var”和“let”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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