有什么理由不放弃“var"吗?

2022-01-24 00:00:00 constants javascript var let

在学习 JavaScript 的过程中,了解到引入 Letconst 是为了解决 Var 关于全局作用域和提升的问题并且如果重新声明也不报错.

In the process of learning JavaScript I learned that Let and const were introduced to fix the problems of Var regarding the global scope and hoisting and not giving an error if re-declared.

现在我可以在不使用 var 的情况下完全编写代码吗?还是我应该暂时了解它们并等到它们被广泛接受"?

Now can I write the code completely without using var ? or should I know about them for now and wait till they becomes widely "acceptable"?

也就是说,如果我暂时只使用letconst,我应该担心兼容性问题吗?

In other words, for the time being should I be worried about compatibility issues if I only used let and const?

推荐答案

直接回答这个问题 - 不,你不能,因为兼容性问题,@suraj 好心提醒我们.

To answer the question directly - no, you can't, because of the compatibility issues, as @suraj kindly reminded us.

话虽如此,在现代 JS 开发中,你越来越不可能使用 var,因为 letconst 具有明显的优势,除了var 的一些特定用途,将使用 BabelJS、TypeScript 甚至现在的 Webpack 2 来转换代码向后兼容性,因为生产代码将在 vanilla JS 中提供.现代 IDE,比如 WebStorm,甚至会默认在 ES6 模式下对你的 var 进行 lint,以将它们更改为 let.

Having said that, in the modern JS development you are increasingly unlikely to use var as let and const have clear advantages, apart from some specific uses of var and will use either BabelJS, TypeScript or even now Webpack 2 to transpile the code for backward compatibility as the production code will be shipped in vanilla JS. Modern IDEs, like WebStorm, will even lint your var's by default in ES6 mode to change them to let.

从问题来看,你还在学习JS,你已经问对了问题,所以我今天推荐使用letconst利用 ES6 的优势,但这会增加处理转译器的复杂性.但是,如果您对此感到满意 - 这就是要走的路.

Judging from the question, you are still in the process of studying JS and you are already asking the right questions, so I would recommend to use today let and const to utilize the advantages of ES6, but that would add the complexity of dealing with the transpilers. But if you are OK with that - this is the way to go.

相关文章