10 個經常使用的 es6 特性

1. const  and letes6

    除了函數做用域以外,增長了塊級做用域和常量。const 定義的綁定不能夠修改,let定義的綁定在{ }不能訪問。以前的 var 若是不在函數做用域內,至關於定義了一個全局變量,而且有變量提高(將變量的聲明提高至所在函數的最前面)。數組

 

2. 數組函數promise

    新增了一些數組處理函數,能夠更加方便的對數組進行操做。app

    let a = Array.foreach( functionA )  functionA 會對函數的每一元素進行操做,a = undefined。函數

    let b = Array.map( functionA ), 與foreach 的不一樣的是map 會返回一個新的數組。this

    let c = Array.filter( functionA ), 與map不一樣的是,filter 返回的數組Array 的一個子集。spa

   let d = Array.find( functuonB ) , 找到符合條件的值立馬返回。rest

   let e = Array.every( checkFunc) , check 每個 element , all ok 則 返回 true, else return false.code

   let g = Array.some( checkFunc), if any element passes the check, retrun ture, else return false.對象

  let  h = Array.reduce(function, initArgument), 提供操做和初始值函數,最終返回一個值。

 

3. 箭頭函數

   ()=> {}    -- 參數函數體。當參數只有一個,函數體只有一行時能夠寫成 a => a*a的形式,省略()和{},其中a*a爲函數的返回值。

    與以前函數不一樣,箭頭函數不會綁定this,arguments,super等局部變量,全部涉及到它們的引用都會沿着向上查找的方式在外層查找。

    因此箭頭函數不能用 apply,call,bind來綁定函數內部的this。

    按詞法做用域,Lexical Scoping just means that it uses  this from the code that contains the Arrow Function.。即從包含箭頭函數的上下文做用域裏去查找this。

    而用 function 定義的函數,則this其實是在函數被調用時發生綁定,它指向什麼徹底取決於函數在哪裏被調用。

 

4.類

  es6 中的類實際上原型繼承的語法糖,constructor就是構造函數,建立一個對象,而在類中添加函數,就是在對象的原型鏈上添加方法。

 

5. 加強的對象字面量

    <1> 能夠引用上下文做用域中的變量

    <2> 直接定義方法

    <3> 定義動態屬性

const color = 'red'
const point = { x: 5, y: 10, color, toString() { return 'X=' + this.x + ', Y=' + this.y + ', color=' + this.color }, [ 'prop_' + 42 ]: 42 }

 

6.模板字符串

   直接在字符串中使用變量,避免使用 + 來鏈接變量。

function hello(firstName, lastName) { return `Good morning ${firstName} ${lastName}! How are you?` }

 

7.默認函數參數

   默認指定函數參數的默認值,當傳入參數的時候會覆蓋默認值。

function sort(arr = [], direction = 'ascending') { console.log('I\'m going to sort the array', arr, direction) }

 

8.解構和剩餘操做符

// 解構
var array = ['red', 'blue', 'green'] var copyOfArray = [...array] //rest opoerator
function printColors(first, second, third, ...others) { console.log('Top three colors are ' + first + ', ' + second + ' and ' + third + '. Others are: ' + others) }

 

9. 從數組中提取須要的值,傳入變量,也包括對象。

 let [first, , third] = [1,2,3];
let obj = {a:100,b:200};
let {a}= obj;

 

10. promise

     promise.then().catch();

 

總結

    1.構造函數可能會被類修飾符替代。

    2. 函數做爲子程序,可能會被箭頭函數替代。

   3.  函數做爲對象方法,可能會被對象方法定義。

相關文章
相關標籤/搜索