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

查看:121
本文介绍了如果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 以便它不会覆盖外部的 x ?

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

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

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天全站免登陆