'let'和'const'ECMAScript 2015(ES6)有什么区别? [英] What is the difference between 'let' and 'const' ECMAScript 2015 (ES6)?

查看:157
本文介绍了'let'和'const'ECMAScript 2015(ES6)有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 ES6 const 之间有什么区别? 。它们都是块作用域,如以下代码中的示例所示:

I'm wondering what is the difference between let and const in ES6. Both of them are block scoped, as the example in the following code:

const PI = 3.14;
console.log(PI);

PI = 3;
console.log(PI);

const PI = 4;
console.log(PI);

var PI = 5;
console.log(PI);

在ES5中,输出将是:

In ES5 the output will be:

3.14
3.14
3.14
3.14

但在ES6中它将是:

3.14
3
4
5

我想知道为什么 ES6 允许更改 const 值,问题是为什么我们现在应该使用'const'?我们可以使用'let'代替吗?

I'm wondering why ES6 allows the change of const value, the question is why should we use 'const' now? we can use 'let' instead?

注意 jsbin 可用于测试,选择 JavaScript 运行 ES5 代码, Traceur 运行它具有 ES6 功能。

Note: jsbin can be used for testing, choose JavaScript to run ES5 code and Traceur to run it with ES6 capabilities.

推荐答案

您所看到的只是一个实现错误。根据 ES6规范维基 const const 是:

What you're seeing is just an implementation mistake. According to the ES6 spec wiki on const, const is:


初始化一次,只读其后绑定form是有用的,在现有实现中有
先例,以const
声明的形式。

A initialize-once, read-only thereafter binding form is useful and has precedent in existing implementations, in the form of const declarations.

这意味着是只读的,就像现在一样。 Traceur和Continuum中的 const 的ES6实现是错误的(他们可能只是忽略了它)

It's meant to be read-only, just like it currently is. The ES6 implementation of const in Traceur and Continuum are buggy (they probably just overlooked it)

这是一个关于Traceur没有实现 const 的Github问题

Here's a Github issue regarding Traceur not implementing const

这篇关于'let'和'const'ECMAScript 2015(ES6)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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