ES6學習

最經常使用的ES6特性

let,const
class,extends,super
arrow functions
template string
destructuring
default
rest argumentsjavascript

let,const

let

ES5沒有塊級做用域名(使用的是var)
let爲javascript增長了塊級做用域,用它所聲明的變量,只在let命令所在的代碼塊內有效。(大括號包圍則造成一個塊級做用域,如函數、循環、判斷、選擇等結構)html

let name = 'zach'
while (true) {
    let name = 'obama'
    console.log(name)  //obama
    break
}
console.log(name)  //zach

var會帶來計數的循環變量泄露爲全局變量的問題java

var a = [];
for (let i = 0; i < 10; i++) {
  a[i] = function () {
    console.log(i);
  };
}
a[6](); // 6

閉包問題react

function iteratorFactory(i){
    var onclick = function(e){
        console.log(i)
    }
    return onclick;
}
var clickBoxs = document.querySelectorAll('.clickBox')
for (var i = 0; i < clickBoxs.length; i++){
    clickBoxs[i].onclick = iteratorFactory(i)
}
//或者這樣寫
for(var i = 0; i < clickBoxs.length;i++){
    clickBox[i].onclick = (function(index){
        return function(){
            console.log(index);
        }
    })(i)
}

const

const聲明的是常量,不能改變
當咱們嘗試去改變用const聲明的常量時,瀏覽器就會報錯。const有一個很好的應用場景,就是當咱們引用第三方庫的時聲明的變量,用const來聲明能夠避免將來不當心重命名而致使出現bug:es6

const monent = require('moment')

class,extends,super

原型、構造函數,繼承
引入了Class(類)這個概念。新的class寫法讓對象原型的寫法更加清晰、更像面向對象編程的語法,也更加通俗易懂。編程

class Animal{
    constructor(){//構造方法
        this.type = 'animal';//this關鍵字則表明實例對象
    }
    says(say){
        console.log(this.type + ' says ' +say);
    }
}
let animal = new Animal();
animal.says("hello");
class Cat extends Animal{
    constructor(){
        super();//它指代父類的實例(即父類的this對象)。
        this.type = 'cat'
    }
}
let cat = new Cat();
cat.says("hello");

constructor內定義的方法和屬性是實例對象本身的,而constructor外定義的方法和屬性則是全部實例對象能夠共享的。segmentfault

super關鍵字,它指代父類的實例(即父類的this對象)。子類必須在constructor方法中調用super方法,不然新建實例時會報錯。這是由於子類沒有本身的this對象,而是繼承父類的this對象,而後對其進行加工。若是不調用super方法,子類就得不到this對象。數組

ES6的繼承機制,實質是先創造父類的實例對象this(因此必須先調用super方法),而後再用子類的構造函數(constructor())修改this。瀏覽器

arrow function(最經常使用的箭頭函數)

若是沒有=>後沒有{},則表示返回=>後的內容服務器

function(i){ return i+1; }//ES5
(i) => i + 1;//ES6

若是方程比較複雜,則須要用{}把代碼包起來:

function(x,y){
   x++;
   y--;
   return x+y;
}
(x,y) => { x++; y--; return x+y;}

長期以來,JavaScript語言的this對象一直是一個使人頭痛的問題,在對象方法中使用this,必須很是當心。

class Animal {
    constructor(){
        this.type = 'animal'
    }
    says(say){
        setTimeout(function(){
            console.log(this.type + ' says ' + say)
        }, 1000)
    }
}
 var animal = new Animal()
 animal.says('hi')  //undefined says hi
//setTimeout中的this指向的是全局對象。

解決辦法

  • 將this傳給self,再用self指代this

says(say){
           var self = this;
           setTimeout(function(){
              console.log(self.type + ' says ' + say)
           }, 1000)
  • 採用bind(this)

says(say){
           setTimeout(function(){
               console.log(this.type + ' says ' + say)
 }.bind(this), 1000)//把window中的this指向當前的this
  • 箭頭函數

當咱們使用箭頭函數時,函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象。並非由於箭頭函數內部有綁定this的機制,實際緣由是箭頭函數根本沒有本身的this,它的this是繼承外面的,所以內部的this就是外層代碼塊的this。

class Animal {
    constructor() {
        this.type = 'animal';
    }
    says(say) {
        setTimeout(
            () => {
                console.log(this.type + ' says ' + say)
            }, 10000)
    }
}
let animal = new Animal();
animal.says("hua");

方便回調函數定義

fetch(url).then((data)=>{
  console.log(data);
  //體現了回調函數的意義,拿到data了接着作什麼
})

template string

原先

$("#result").append(
  "There are <b>" + basket.count + "</b> " +
  "items in your basket, " +
  "<em>" + basket.onSale +
  "</em> are on sale!"
);

如今

let obj = {
        count:2
    }
document.getElementById("template").innerHTML = `There ar <b>${obj.count}</b> items`;

用反引號( `)來標識起始,用${}來引用變量,並且全部的空格和縮進都會被保留在輸出之中,

destructuring

ES6容許按照必定模式,從數組和對象中提取值,對變量進行賦值,這被稱爲解構(Destructuring)

let dog = {type: 'animal', many: 2}
let { type, many} = dog
console.log(type, many)

default,rest

default 默認值

傳統作法

function animal(type){
    type = type || 'cat'  
    console.log(type)
}
animal()

es6

function animal(type = 'cat'){
    console.log(type);
}
animal();

says(say) {
            setTimeout(
                (hello = 'hualy') => {
                    console.log(this.type + ' says ' + say + hello)
                }, 10000)
        }

rest(而若是不用ES6的話,咱們則得使用ES5的arguments。)

function animals(...types){
    console.log(types)
}
animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]

import,export

import和export對應es6的module功能
咱們以前寫的Javascript一直都沒有模塊化的體系,沒法將一個龐大的js工程拆分紅一個個功能相對獨立但相互依賴的小工程,再用一種簡單的方法把這些小工程鏈接在一塊兒。

這有可能致使兩個問題:

  • 一方面js代碼變得很臃腫,難以維護

  • 另外一方面咱們經常得很注意每一個script標籤在html中的位置,由於它們一般有依賴關係,順序錯了可能就會出bug

在es6以前爲解決上面提到的問題,咱們得利用第三方提供的一些方案,主要有兩種CommonJS(服務器端)和AMD(瀏覽器端,如require.js)。模塊化

es6的module功能,它實現很是簡單,能夠成爲服務器和瀏覽器通用的模塊解決方案。

ES6模塊的設計思想,是儘可能的靜態化,使得編譯時就能肯定模塊的依賴關係,以及輸入和輸出的變量。CommonJS和AMD模塊,都只能在運行時肯定這些東西。

ES5模塊化(require module exports)

  • require.js書寫

首先define

//想要在index.js文件中使用content.js的返回結果
//content.js
define('content.js',function(){
    return 'A cat';
})

而後require

//index.js
require(['./content.js'],function(animal){
    console.log(animal);//A cat
})
  • CommonJS書寫

//index.js
var animal = require('./content.js');
//content.js
module.exports = 'A cat';

ES6模塊化(import,export)

//index.js
import animal from './content'
//content.js
export default 'A cat'

ES6 module 的其餘高級用法

//content.js
export default 'A cat'    //變量
export function say(){    //函數
   return 'Hello'!
}
exoport const type = 'dog'  //類
export命令除了輸出變量,還能夠輸出函數,甚至是類(react的模塊基本都是輸出類)

//index.js
import {say,type} from './content'
let says = say()
console.log(`The ${type} say ${says}`)

大括號裏面的變量名,必須與被導入模塊(content.js)對外接口的名稱相同
但願輸入content.js中輸出的默認值(default), 能夠寫在大括號外面。

//index.js
import abc,{say,type} from './content'
let says = say();
console.log(`The ${type} says ${says] to ${abc}`)

修改變量名

//index.js
import abc, { say, type as animalType } from './content'  
let says = say()
console.log(`The ${animalType} says ${says} to ${abc}`)  
//The dog says Hello to A cat

模塊的總體加載
除了指定加載某個輸出值,還可使用總體加載,即用星號(*)指定一個對象,全部輸出值都加載在這個對象上面。

//index.js
import animal, * as content from './content'  
let says = content.say()
console.log(`The ${content.type} says ${says} to ${animal}`)  
//The dog says Hello to A cat

本文是根據下面的文章加上本身的理解寫的~
參考連接:

30分鐘掌握ES6/ES2015核心內容上
30分鐘掌握ES6/ES2015核心內容下

相關文章
相關標籤/搜索