如果babel将let和const转换为var,那有什么区别? [英] If babel converts let and const to var, what's the difference?

查看:1263
本文介绍了如果babel将let和const转换为var,那有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试过 babel转换器,它将All let,const和var转换为var,总而言之,我们的代码使用有什么不同?


我已阅读文档和我知道let,const和var 之间有什么区别,但是如果所有这些文件最终都转换为var 差异是什么?这意味着在性能甚至范围上不应有任何有意义的差异!

I've tried the babel transpiler, and it converts All let, const and var to just var, so in all, what's the difference in our code usage?
I have read documents and I know what's the difference between let, const and var, but if all of them are eventually converted to var, what's the difference? it means that there shouldn't be any meaningful differences in performance or even scope!

更新(02.14.2019):基于答案我知道范围确实很重要,即使它们被转换为var,babel仍然保留范围的含义。我的问题仍然是关于性能,是否有任何有意义的性能差异?

Update(02.14.2019) : Based on the answers I understood that scope does matter and even though they are converted to var, babel keeps the meaning of scope. My question remains about the performance, is there any meaningful difference in performance?

我附加了转换器的输入和输出,更复杂的情况


输入

I've attached the input and output of the transpiler, with a more complex scenario
input:

let a = 1;

for (let a = 0; a !== 0;) {
  for (let a = 0; a !== 0;) {}
}

输出

"use strict";

var a = 1;

for (var _a = 0; _a !== 0;) {
  for (var _a2 = 0; _a2 !== 0;) {}
}


推荐答案

Babel将ES6语法转换为ES5语法(或任何来源和你正在处理的JS的目标版本。)

Babel converts the ES6 syntax to ES5 syntax (or whatever source and target versions of JS you are dealing with).

这通常会失去代码中的一些细微差别,但你看的是一个非常简单的例子。

This will often lose some of the nuances in the code, but you are looking at a very trivial example.

请考虑这一点:

let x = 1;

{
  // Inside a block, this is a different x
  let x = 2; 
  console.log(x);
}

console.log(x);

Babel会将其转换为:

Babel will convert that to:

"use strict";

var x = 1;
{
  // Inside a block, this is a different x
  var _x = 2;
  console.log(_x);
}
console.log(x);

了解它如何重命名内部 x 所以它不会覆盖外部的那个?

See how it renames the inner x so that it doesn't overwrite the outer one?

它在ES5中尽可能多地表达ES6的效果,即使结果很难看(因为ES6的优雅功能不可用)。

It expresses the effect of the ES6 as much as it can in ES5, even if the result is ugly (because the elegant feature from ES6 is not available).

这篇关于如果babel将let和const转换为var,那有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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