概述
ECMAScript 6(以下簡稱ES6)是JavaScript語言的下一代標準。因爲當前版本的ES6是在2015年發佈的,所以又稱ECMAScript 2015。
let,const
都是用來聲明變量的,對應ES5的var,但是特性更好:
let
var name = 'zach'
while (true) {
var name = 'obama'
console.log(name) //obama
break
}
console.log(name) //obama
ES5的var只有全局作用域和函數作用域,這樣容易導致某些情況下全局變量被方法更改的問題。而let則是塊級作用域,不影響全局變量。如:
let name = 'zach'
while (true) {
let name = 'obama'
console.log(name) //obama
break
}
console.log(name) //zach
另外一個var帶來的不合理場景就是用來計數的循環變量泄露爲全局變量,看下面的例子:
var a = [];
for (var i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 10
上面的代碼中 變量i是var聲明的,在全局範圍內都有效。所以每次循環,需要輸出的i都會累加。到最後所有的方法指向的都是最後的i=10。而如果使用let則不會出現這個問題
var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 6
再來看一個例子:不用ES6
let clickBoxs = document.querySelectorAll('.btn')
for (var i = 0; i < clickBoxs.length; i++) {
clickBoxs[i].onclick = function () {
console.log(i)
}
}
點擊不同的clickBox顯示不同的i,上面的例子,點擊任何一個按鈕都是等於clickBoxs.length
下面來解決它:
function iteratorFactory(i) {
var onclick = function (e) {
console.log(i)
}
return onclick;
}
var clickBoxs = document.querySelectorAll('.btn2')
for (var i = 0; i < clickBoxs.length; i++) {
clickBoxs[i].onclick = iteratorFactory(i)
}
而如果使用ES6則只要將對應的var改爲let即可。不用這麼麻煩。
const
const使用時必須在聲明處賦值,並且之後不能做更改。比較常用的用法是用來聲明工具對象。如const util=require(‘moment’)
防止該對象被更改避免錯誤。
class,extends,super
類似於java中的用法:
class Animal {
constructor() {
this.type = 'animal'
}
says(say) {
console.log(this.type + ' says ' + say)
}
}
let animal = new Animal()
animal.says("miao~")//animal says miao~
class People extends Animal {
constructor() {
super()
this.type = "people"
}
}
let people = new People()
people.says("hello")//people says hello
super關鍵字,大知道父類的實例(即父類的this對象)。自雷必須在constructor方法中調用super方法,否則新建實例時會報錯。這是因爲自雷沒有自己的this對象。而是繼承父類的this對象然後再加工。
ES6的繼承機制,實質是先創造父類的實例對象this(所以必須先調用super方法),然後再用子類的構造函數修改this。
箭頭函數
優點:
- 簡潔(如果沒有{}符號,則表達式的結果爲方法返回值return)
- 創建時this對象使用當時定義時所在的對象。(普通方法是調用時的對象)
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}
this對象問題:
class Animal {
constructor() {
this.type = 'animal'
}
says(say) {
setTimeout(function () {
console.log(this.type + ' says ' + say)
}.bind(this), 1000)
}
}
var animal = new Animal()
animal.says('hi') //undefined says hi
在ES5中該方法執行會報錯,因爲執行延遲後方法中的this指向全局對象。
解決方法有兩種:
- 將this對象傳給變量,再在延遲過後使用該對象
says(say){
var self = this;
setTimeout(function(){
console.log(self.type + ' says ' + say)
}, 1000)
2.使用bind(this)
says(say){
setTimeout(function(){
console.log(this.type + ' says ' + say)
}.bind(this), 1000)
3.使用箭頭函數:
class Animal {
constructor(){
this.type = 'animal'
}
says(say){
setTimeout( () => {
console.log(this.type + ' says ' + say)
}, 1000)
}
}
var animal = new Animal()
animal.says('hi') //animal says hi
模版字符串
··符號,ES5中的寫法是字符串需要+=或者合成一個長串,不便於閱讀又十分麻煩。而使用模版字符串,則大大簡化。
$("#result").append(
"There are <b>" + basket.count + "</b> " +
"items in your basket, " +
"<em>" + basket.onSale +
"</em> are on sale!"
);
模板字符串:(變量使用${})
$("#result").append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`);
解構
ES6允許按照一定模式,從數組和對象中提取值,對變量進行賦值,這被稱爲解構(Destructuring)。
let student = "stu"
let teacher = "tea"
let classRoom = {student: student, teacher: teacher}//es5
console.log(classRoom)//{student: "stu", teacher: "tea"}
let classRoom1 = {student, teacher}//es6
console.log(classRoom1)//{student: "stu", teacher: "tea"}
使用ES6,如果key等於對象名,則可以這樣
let cat = 'ken'
let dog = 'lili'
let zoo = {cat, dog}
console.log(zoo) //Object {cat: "ken", dog: "lili"}
相反,可以這樣寫:相當於從對象中取出該對象key並賦值
let dog = {type: 'animal', many: 2}
let { type, many} = dog
console.log(type, many) //animal 2
default,rest
default默認值,即在方法傳入時,如果入參爲空,可以指定一個默認值
//傳統寫法
function animal(type){
type = type || 'cat'
console.log(type)
}
animal() //cat
//ES6寫法
function animal(type='cat'){
console.log(type)
}
rest語法:將傳入的對象都放入數組中,如果入參爲空,則types是一個空數組
function animals(...types){
console.log(types)
}
animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]
import,export
導入、導出。ES6模塊的設計思想,是儘量的靜態化,使得編譯時就能確定模塊的依賴關係,以及輸入和輸出的變量。
用法:
//index.js
import animal from './content'
//content.js
export default 'A cat'
其他高級用法:
//content.js
export default 'A cat'
export function say(){
return 'Hello!'
}
export const type = 'dog'
exprot除了可以輸出變量,輸出函數,還能輸出類(react中基本都是輸出類)
//index.js
import { say, type } from './content'
let says = say()
console.log(`The ${type} says ${says}`) //The dog says Hello
如果還希望輸入content.js中輸出的默認值(default), 可以寫在大括號外面。
//index.js
import animal, { say, type } from './content'
let says = say()
console.log(`The ${type} says ${says} to ${animal}`)
//The dog says Hello to A cat
- 修改improt的變量名(當有重名的變量時可用,as)
//index.js
import animal, { say, type as animalType } from './content'
let says = say()
console.log(`The ${animalType} says ${says} to ${animal}`)
//The dog says Hello to A cat
- 使用號整體加載,通常星號結合as一起使用比較合適。
//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
計算屬性名稱語法:
對象的屬性名,可以像數組下標一樣使用[]符號獲取對應的屬性值。並且[]符號內容可以是變量
也可以進行計算,取計算的結果作爲取值key
var i = 0;
var a = {
['foo' + ++i]: i,
['foo' + ++i]: i,
['foo' + ++i]: i
};
console.log(a.foo1); // 1
console.log(a.foo2); // 2
console.log(a.foo3); // 3