ES6
代碼盡量標簽化語義化、優先使用標簽,class基于功能命名、基于內容命名、基于表現命
布局提高css重用率,簡潔、明了、無后患(添加刪除內容,窗口縮放,不會崩掉)
=>箭頭函數、特性1
function和return,一些小括號、大括號以及分號可以省略
//ES5
s.filter(function(val){
return val > 0;
})
//ES6 當只有一個參數的簡單函數時,語法為:標識符 => 表達式
s.filter(val => val>0);
//ES5
=>箭頭函數、特性2
=>箭頭函數內的this值繼承自外圍作用域
//ES5
addAll: function addAll(pieces) {
var self = this;
function pact(pieces) {
self.add(pieces);
};
},
//ES6
addAll: function addAll(pieces) {
function pact(pieces => this.add(pieces));
},
var: 聲明變量,全局作用域和函數作用域
let: 聲明變量,塊級作用域
var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 6 {}為一個塊
cont: 聲明常量,之后值不能改變
應用場景: 當我們引用第三方庫的時聲明的變量,用const來聲明可以避免未來不小心重命名而導致出現bug,當我們嘗試去改變用const聲明的常量時,瀏覽器就會報錯
class, extends, super
這三個特性涉及了ES5中最令人頭疼的的幾個部分:原型、構造函數,繼承...你還在為它們復雜難懂的語法而煩惱嗎?你還在為指針到底指向哪里而糾結萬分嗎?
有了ES6我們不再煩惱!
ES6提供了更接近傳統語言的寫法,引入了Class(類)這個概念。新的class寫法讓對象原型的寫法更加清晰、更像面向對象編程的語法,也更加通俗易懂。
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之間可以通過extends關鍵字實現繼承,這比ES5的通過修改原型鏈實現繼承,要清晰和方便很多。上面定義了一個Cat類,該類通過extends關鍵字,繼承了Animal類的所有屬性和方法。
super關鍵字,它指代父類的實例(即父類的this對象)。子類必須在constructor方法中調用super方法,否則新建實例時會報錯。這是因為子類沒有自己的this對象,而是繼承父類的this對象,然后對其進行加工。如果不調用super方法,子類就得不到this對象。
ES6的繼承機制,實質是先創造父類的實例對象this(所以必須先調用super方法),然后再用子類的構造函數修改this。
arrow function
ES6最最常用的一個新特性
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}
除了看上去更簡潔以外,arrow function還有一項超級無敵的功能!
長期以來,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)
但現在我們有了箭頭函數,就不需要這么麻煩了:
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
當我們使用箭頭函數時,函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象。
并不是因為箭頭函數內部有綁定this的機制,實際原因是箭頭函數根本沒有自己的this,它的this是繼承外面的,因此內部的this就是外層代碼塊的this。
template string
當我們要插入大段的html內容到文檔中時,傳統的寫法非常麻煩。
$("#result").append(
"There are <b>" + basket.count + "</b> " +
"items in your basket, " +
"<em>" + basket.onSale +
"</em> are on sale!"
);
我們要用一堆的'+'號來連接文本與變量,而使用ES6的新特性模板字符串``后,我們可以直接這么來寫:
$("#result").append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`);
用反引號(`)來標識起始(即英文輸入法+ESC下方那個~鍵
),用${}`來引用變量,而且所有的空格和縮進都會被保留在輸出之中,是不是非常爽?!
destructuring
ES6允許按照一定模式,從數組和對象中提取值,對變量進行賦值,這被稱為解構(Destructuring)。
看下面的例子:
let cat = 'ken'
let dog = 'lili'
let zoo = {cat: cat, dog: dog}
console.log(zoo) //Object {cat: "ken", dog: "lili"}
用ES6完全可以像下面這么寫:
let cat = 'ken'
let dog = 'lili'
let zoo = {cat, dog}
console.log(zoo) //Object {cat: "ken", dog: "lili"}
也可以這么寫:
let dog = { type: 'animal', many: 2 }
let dog = { type, many }
console.log(type, many) //animal 2
default, rest
default很簡單,意思就是默認值。大家可以看下面的例子,調用animal()方法時忘了傳參數,傳統的做法就是加上這一句type = type || 'cat' 來指定默認值。
function animal(type){
type = type || 'cat'
console.log(type)
}
animal()
如果用ES6我們而已直接這么寫:
function animal(type = 'cat'){
console.log(type)
}
animal()
import、export
這兩個家伙對應的就是es6自己的module功能。
我們之前寫的Javascript一直都沒有模塊化的體系,無法將一個龐大的js工程拆分成一個個功能相對獨立但相互依賴的小工程,再用一種簡單的方法把這些小工程連接在一起。
這有可能導致兩個問題:
1.一方面js代碼變得很臃腫,難以維護
2.另一方面我們常常得很注意每個script標簽在html中的位置,因為它們通常有依賴關系,順序錯了可能就會出bug
在es6之前為解決上面提到的問題,我們得利用第三方提供的一些方案,主要有兩種CommonJS(服務器端)和AMD(瀏覽器端,如require.js)。
而現在我們有了es6的module功能,它實現非常簡單,可以成為服務器和瀏覽器通用的模塊解決方案。
ES6模塊的設計思想,是盡量的靜態化,使得編譯時就能確定模塊的依賴關系,以及輸入和輸出的變量。CommonJS和AMD模塊,都只能在運行時確定這些東西。
上面的設計思想看不懂也沒關系,咱先學會怎么用,等以后用多了、熟練了再去研究它背后的設計思想也不遲!好,那我們就上代碼...
傳統的寫法
首先我們回顧下require.js的寫法。假設我們有兩個js文件: index.js和content.js,現在我們想要在index.js中使用content.js返回的結果,我們要怎么做呢?
首先定義:
//content.js
define('content.js', function(){
return 'A cat';
})
然后請求:
//index.js
require(['./content.js'], function(animal){
console.log(animal); //A cat
})
那CommonJS是怎么寫的呢?
//content.js
module.exports = 'A cat'
//index.js
var animal = require('./content.js')
ES6的寫法
//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!'
}
export const type = 'dog'
上面可以看出,export命令除了輸出變量,還可以輸出函數,甚至是類(react的模塊基本都是輸出類)
//index.js
import { say, type } from './content'
let says = say()
console.log(`The ${type} says ${says}`) //The dog says Hello
這里輸入的時候要注意:大括號里面的變量名,必須與被導入模塊(content.js)對外接口的名稱相同。
如果還希望輸入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
修改變量名
此時我們不喜歡type這個變量名,因為它有可能重名,所以我們需要修改一下它的變量名。在es6中可以用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
模塊的整體加載
除了指定加載某個輸出值,還可以使用整體加載,即用星號(*)指定一個對象,所有輸出值都加載在這個對象上面。
//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
通常星號*結合as一起使用比較合適。
終極秘籍
考慮下面的場景:上面的content.js
一共輸出了三個變量(default, say, type
),假如我們的實際項目當中只需要用到type
這一個變量,其余兩個我們暫時不需要。我們可以只輸入一個變量:
import { type } from './content'
由于其他兩個變量沒有被使用,我們希望代碼打包的時候也忽略它們,拋棄它們,這樣在大項目中可以顯著減少文件的體積。
ES6幫我們實現了!
不過,目前無論是webpack還是browserify都還不支持這一功能...
如果你現在就想實現這一功能的話,可以嘗試使用rollup.js
他們把這個功能叫做Tree-shaking,哈哈哈,意思就是打包前讓整個文檔樹抖一抖,把那些并未被依賴或使用的東西統統抖落下去。。。