Typescript 1.5中的"var"和"let" [英] 'var' and 'let' in Typescript 1.5

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

问题描述

在Typescript中使用" var "或" let "到底有什么区别?我知道'let'允许将变量进一步定义到作用域中,而不必在该作用域之外使用它.对于for循环中的迭代器来说,这显然是一个不错的优势.我知道这是ES6的定义,因此就ESX6而言,在"var"和"let"方面看起来应该几乎相同.

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

基本上,当打字稿编译让变量传给ES5 javascript时会发生什么?

解决方案

此处是有关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'.

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?

Basically, what is happening when typescript compiles let variables to ES5 javascript?

解决方案

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

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

This code:

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

Compiles to:

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

Here is some more information regarding let.

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

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