1. 程式人生 > >es6常用特性學習總結

es6常用特性學習總結

常用到的es6方法,或者說20%的內容,但是在實際應用場景中佔了80%的內容。
1、預設引數

es5寫法:
var link = function(height, color) {
    var height = height || 50,
        color = color || 'red';
    ...
}
*************************************
es6寫法:
var link = function(height = 50, color = 'red'){
    ...
}
解決問題:1)當引數是數字0時,es5的寫法是有問題的。JavaScript會解析為false,
導致賦值錯誤;2
)es6的寫法更優雅簡潔。

2、模板物件

es5寫法:
    var name = 'your name is' + first + '' + last + '.';
    var url = 'http://localhost:8080/api/messages/' + id;

es6寫法:
    var name = `your name is ${first} ${last}.`;
    var url = `http://localhost:8080/api/messages/${id}`;
解決問題:1)es5中通過加操作符來操作字串中的變數,會引入很多單引號,稍不留意,會導致出錯,特殊字元還需要轉義,比較麻煩。2
)es6的寫法大大降低了出錯的可能,更簡潔。

3、多行字串

es5寫法:
var roadPoem = 'Then took the other, as just as fair,'
    + 'And having perhaps the better claimnt'
    + 'Because it was grassy and wanted wear,nt'
    + 'Though as for that the passing therent'
    + 'Had worn them really about the same,nt';
var fourAgreements = 'You have the
right to be you.n You can only be you when you do your best.'; es6寫法: var roadPoem = `Then took the other, as just as fair, And having perhaps the better claim Because it was grassy and wanted wear, Though as for that the passing there Had worn them really about the same,`; var fourAgreements = `You have the right to be you. You can only be you when you do your best.`; 解決問題:1)es5中超長字串的寫法通過字串相加實現,會引入很多單引號,稍不留意,會導致出錯,特殊字元還需要轉義,比較麻煩。2)該方法和模板物件異曲同工。

4、解構賦值(可以理解為批量賦值,對於等號左右結構型別一致的變數和值,一一對應賦值)

es5寫法:
    var data = $('body').data(),
        house = data.house,
        mouse = data.mouse;


es6寫法:
    var {house,mouse} = $('body').data();
    var {a,b} = {a:1,b:2};//=>a=1;b=2
    注意物件的解構,左邊的引數必須和右邊物件的屬性名一樣,而陣列的解構不需要
解決問題:1)es5中獲取陣列或物件的鍵值並賦值是個常見的操作,舊的方式是取值,並一一賦值給新變數,相當於同一個操作執行了很多遍,比較囉嗦。2)es6的寫法節省了程式碼量,實現了批量賦值,提高了效率。

5、箭頭函式

es5寫法:
    var _this = this;
    $('.btn').click(function(event){
        _this.sendData();
    })

es6寫法:
    $('.btn').click((event) => {
        this.sendData();
    })
解決問題:1)es5中的this一不小心就會被改變,箭頭函式,函式體內的this物件,就是定義時所在的物件,而不是呼叫時的物件。不必用self = this或.bind來實現this的指向變更2)箭頭函式寫法更優雅。

6、塊級作用域let和const

es5寫法:
    function calculateTotalAmount(vip) {
        var amount = 0;
        if(vip) {
            var amount = 1;
        }
        {
            var amount = 10;
        }
        return amount;
    }
    console.log(calculateTotalAmount(true));
    結果返回10,因為es5沒有塊級作用域,只有全域性域和函式域,因此導致錯誤。

es6寫法:
    function calculateTotalAmount(vip) {
        var amount = 0;
        if(vip) {
            let amount = 1;
        }
        {
            let amount = 10;
        }
        return amount;
    }
    console.log(calculateTotalAmount(true));    
    結果返回0,因為塊級作用域用了let,但是外部有var amount = 0,會覆蓋。為了解決問題,引入const,常量,也是塊級作用域,但是值不能被修改。
    function calculateTotalAmount(vip) {
        const amount = 0;
        if(vip) {
            let amount = 1;
        }
        {
            let amount = 10;
        }
        return amount;
    }
    console.log(calculateTotalAmount(true));        
    結果返回1.
解決問題:1)es5中的變數宣告很簡單,但是一不小心就會引入全域性變數,沒有名稱空間導致變數汙染。在es5中可以用閉包的方法實現名稱空間,但是較複雜2)es6的寫法使得JavaScript更符合常見語言的思路。

7、class

es5面向物件程式設計有很多種方法,比較複雜。es6使用關鍵字 classsuperextends實現了類的建立、繼承等面向物件思想。如下:
class Animal {
    constructor(){
        this.type = 'animal'
    }
    says(say){
        console.log(this.type + 'says' + say)
    }
}

let animal = new Animal()
animal.says('hello')//animal says hello

class Cat extends Animal {
    constructor(){
        super()
        this.type = 'cat'
    }
}

let cat = new Cat()
cat.says('hello') //cat says hello

講解:首先用class定義了一個類,裡面的constructor方法,是構造方法,而this關鍵字代表了例項物件。簡單地說,constructor內定義的方法和屬性是例項物件自己的,而constructor外定義的方法和屬性是所有例項物件可以共享的。

    class 完全可以看作是es5建構函式的另一種寫法,使用的時候得也是通過new命令來生成例項物件如:
    class Test{
    ....
    }
    typeof Test //'function'
    Test === Test.prototype.constructor //true

    let b = new Test();
    class之間通過extends關鍵字實現繼承,比es5通過原型鏈實現繼承清晰方便。

    super關鍵字,指代父類的例項(即父類的this物件)。子類必須在constructor方法中呼叫super方法,否則新建例項時會報錯。這是因為子類沒有自己的this物件,而是繼承父類的this物件,然後對其進行加工,如果不呼叫super方法,子類就得不到this物件。

    es6的繼承機制,實質是先創造父類的例項物件this(所以必須先呼叫super方法),然後再用子類的建構函式修改thisclass的靜態方法只能被類或者子類呼叫,不能被例項物件呼叫。

    class的靜態屬性class Foo{ static prop = 1;} prop即為靜態屬性。

    class的例項屬性可以用等式,寫入類的定義之中。如:class MyClass { myProp = 42; constructor(){}} 。在類的例項中,可以讀取該屬性。
    new是從建構函式生成例項的命令,es6引入了new.target屬性,該方法一般用於建構函式中,返回new命令作用的那個建構函式名。