原文: http://pij.robinqu.me/JavaScript_Core/ECMAScript/es6/es6_syntax_features.htmlhtml
ES6包含了不少万众期待的特性支持:git
里面众多的特性都是让Javascript看起来更规范的好东西,可是大部分都没有被普遍支持。咱们仅介绍其中已经至少被一种浏览器和node --harmony
下支持的。es6
在写这篇文章的时候,有以下特性是较为普遍支持的:github
对,就这么多了。前三个是为了解决变量声明、定义的问题,而最后一个则影响最大。会在单独篇幅中介绍。下文只介绍前三个特性。浏览器
var
is scoped to the nearest function block (or global if outside a function block)let
is scoped to the nearest enclosing block (or global if outside any block),不少文献、书籍都建议将for循环的起始变量i
、len
等放置到函数做用于的顶部声明,以免后续变量持续存在所形成的迷惑。app
function() { for(var i=0,len=5;i<len;i++) { //body } console.log(i,len);=> 5,5 }
这是由于ES5的Javascript的不支持块级做用域,变量仅仅被限制到函数做用域内。编辑器
注意在node中,你须要同时加入--harmony
和--use-strict
来启动,才会支持let
。不然会报错: SyntaxError: Illegal let declaration outside extended mode
。ide
在ES6内,能够经过let来定义块级做用域的变量:函数
function() { for(let i=0,len=5;i<len;i++) { //body } console.log(i,len) // throw Reference Error }
最后一个,函数定义的做用域问题:
function f() { console.log('I am outside!'); } (function () { if(false) { // What should happen with this redeclaration? function f() { console.log('I am inside!'); } } f(); }());
如上代码,在ES5时代,每一个浏览器都会得出不一样的结果。可是ES6中,函数定义只在块级做用域内有效,结果很明确。
const关键字定义一个块级做用域的常量变量。
const a = "You shall remain constant!"; // SyntaxError: Assignment to constant variable a = "I wanna be free!";
yield
后面有一连串有关Generator和Iterator的内容,会在另一片文章内详细介绍: Javascript Generator。