为什么var不被弃用? [英] Why is var not deprecated?

查看:191
本文介绍了为什么var不被弃用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近ES6发布后,许多消息来源建议我使用const和let代替var,并且我应该停止在我的JavaScript中使用var。

Lately after ES6 released, many sources suggested that I use "const" and "let" instead of "var", and that I should stop using "var" in my JavaScript.

我想知道的是,如果var在所有观点上都没有let的优势,那么为什么他们不修复var,甚至弃用var而不是让他们一起去彼此?

What I wonder is, if "var" has no advantage over "let" in all points of view, then why didn't they just fix var, or even deprecate "var" instead of letting them go along side each other?

推荐答案

向后兼容性。



你是对的在说使用 var - 如果你在函数的开头定义它们的含义基本相同。

Backwards compatibility.

You're right in saying there is no real advantage to using var over let - if you define them at the start of a function their meaning is basically identical.

你没有理由使用 var 编写新代码(mayb除外) e ,如果相关)。

You're right that there is no real reason to write new code using var (except maybe this, if relevant).

互联网上有几十年的页面,没有人会重写它们。从语言中删除 var 并没有什么好处。对于像解释的HTML和Javascript这样的语言 - 后向兼容性是绝对必要的。

There are pages on the internet that are decades old though, and no one is going to rewrite them. There is nothing really to gain by removing var from the language. For languages like HTML and Javascript that are interpreted - backward compatability is absolutely mandatory.

这也是他们选择不重新定义 var的原因。请使用以下示例代码;

That is also why they chose not to simply redefine var. Take the following example code;

// THIS IS AN EXAMPLE OF BAD CODE. DO NOT COPY AND PASTE THIS.
if (logic) {
    var output = "true"
} else {
    var output = "false"
}
console.log(output)

如果 var 被更改为行为像然后 console.log 会因为范围不同而导致引用错误。

If var was changed to behave like let then the console.log would cause a reference error because of the scope difference.

这篇关于为什么var不被弃用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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