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

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

问题描述

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

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 中它会是:

But in ES6 it will be:

3.14
3
4
5

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

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 规范 wiki on constconst 是:

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

初始化一次,之后只读的绑定形式很有用,并且具有现有实现中的先例,以 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)

这里有一个 Github 问题,关于 Traceur 没有实现 const

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

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