ES6语法特性 - ES6 - ECMAScript特性 - Javascript核心

原文: http://pij.robinqu.me/JavaScript_Core/ECMAScript/es6/es6_syntax_features.htmlhtml

源代码: https://github.com/RobinQu/Programing-In-Javascript/blob/master/chapters/JavaScript_Core/ECMAScript/es6/es6_syntax_features.mdnode

  • 本文须要补充更多例子
  • 本文存在批注,但该网站的Markdown编辑器不支持,因此没法正常展现,请到原文参考。

ES6语法特性

ES6包含了不少万众期待的特性支持:git

  • arrow functions
  • const
  • let
  • default function params
  • rest parameters
  • call(...)
  • array(...)
  • class
  • computed properties
  • modules
  • for...of
  • Array comprehensions
  • Generator comprehensions
  • Iterators
  • yield
  • Template Strings
  • block-level declaration
  • destructing
  • promoise

里面众多的特性都是让Javascript看起来更规范的好东西,可是大部分都没有被普遍支持。咱们仅介绍其中已经至少被一种浏览器和node --harmony下支持的。es6

在写这篇文章的时候,有以下特性是较为普遍支持的:github

  • let1
  • const2
  • Block-delvel declaration
  • for-of
  • yield

对,就这么多了。前三个是为了解决变量声明、定义的问题,而最后一个则影响最大。会在单独篇幅中介绍。下文只介绍前三个特性。浏览器

let和block-level declaration

  • 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循环的起始变量ilen等放置到函数做用于的顶部声明,以免后续变量持续存在所形成的迷惑。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 modeide

在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关键字定义一个块级做用域的常量变量。

const a = "You shall remain constant!";

// SyntaxError: Assignment to constant variable
a = "I wanna be free!";

yield

yield后面有一连串有关Generator和Iterator的内容,会在另一片文章内详细介绍: Javascript Generator

相关文章
相关标签/搜索