ES6常用語法簡介import export
let與var用法區別
//var
var a = [];
for (var i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 10
------------------------------
//let
var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 6
------------------------------
//如果不用 let 實現類似功能
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)
}
class, extends, super
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
的通過修改原型鏈實現繼承,要清晰和方便很多。
super
關鍵字,它指代父類的實例(即父類的this
對象)。子類必須在constructor
方法中調用super
方法,否則新建實例時會報錯。
這是因為子類沒有自己的this
對象,而是繼承父類的this
對象,然后對其進行加工。如果不調用super
方法,子類就得不到this
對象。
ES6
的繼承機制,實質是先創造父類的實例對象this
(所以必須先調用super
方法),然后再用子類的構造函數修改this
。
箭頭函數 arrow function
function(i){ return i + 1; } //ES5
(i) => i + 1 //ES6
如果方程比較復雜,則需要用{}
把代碼包起來:
//es5
function(x, y) {
x++;
y--;
return x + y;
}
//es6
(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
指向的是全局對象。所以為了讓它能夠正確的運行,傳統的解決方法有兩種:
1.第一種是將this
傳給self
,再用self
來指代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)
}
但現在我們有了箭頭函數,就不需要這么麻煩了:
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
//不用模板字符串 寫法
$("#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!
`);
用反引號(`)來標識起始,用
${}
來引用變量,而且所有的空格和縮進
都會被保留在輸出之中(這個需要注意)
解構 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 { type, many} = dog
console.log(type, many) //animal 2
默認值 default
function animal(type){
type = type || 'cat'
console.log(type)
}
animal()
//ES6
function animal(type = 'cat'){
console.log(type)
}
animal()
展開操作符 rest arguments (...)
function animals(...types){
console.log(types)
}
animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]
import export
傳統的寫法CommonJS(服務器端)和AMD(瀏覽器端,如require.js)
AMD寫法
//content.js
define('content.js', function(){
return 'A cat';
})
//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的寫法
//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'
//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
一起使用比較合適。