'let'和'const'ECMAScript 6之间的区别是什么? [英] What is the diffrence between 'let' and 'const' ECMAScript 6?

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

问题描述

我想知道ECMAScript 6中let和const之间的区别是什么。我的意思是两个都是block的范围,例如下面的代码:

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

PI = 3;
console.log(PI);

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

var PI = 5;
console.log(PI);在ECMAScript 5中的

输出将为:

  3.14 
3.14
3.14
3.14

,但在ECMAScript 6中,它将是:

  3.14 
3
4
5

我想知道为什么ECMAScript 6允许更改const值,问题是为什么要现在使用'const'?我们可以使用'let'吗?



注意 jsbin 可以用于测试,选择 Javascript 来运行ECMAScript 5代码和 Traceur 以使用ECMAScript 6功能运行。

解决方案

你所看到的只是一个实现错误。根据 const 上的ES6规范wiki >, const 是:


一个初始化一次,只读后绑定表单是有用的,并且在现有实现中具有
先例,形式为const
声明。


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



这是一个关于Traceur不实现 const = / code> 的Github问题


I'm wondering what is the difference between let and const in ECMAScript 6. I mean both of them are block scoped, as 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);

in ECMAScript 5 the output will be:

3.14
3.14
3.14
3.14

but in ECMAScript 6 it will be:

3.14
3
4
5

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

Note: jsbin can be used for testing, choose Javascript to run ECMAScript 5 code and Traceur to run it with ECMAScript 6 capabilities.

解决方案

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

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

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)

Here's a Github issue regarding Traceur not implementing const

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

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