0%

ES6-shorthand

函式的縮寫

1
2
3
const sayHi = function(){

}

可以將function縮寫為

1
2
3
const sayHi(){

}

屬性縮寫

若要透過函式回傳一個物件,通常會這樣寫

1
2
3
4
5
6
function makePoint( x, y){
return{
x:x
y:y
}
}

但是在ES6可以這樣寫

1
2
3
4
5
6
function makePoint( x, y){
return{
x,
y
}
}

計算屬性

1
2
3
4
5
6
7
function createObj( key, value){
const obj={}
obj[key] = value
return obj
}
const person = createObj('name','Ken')
//'name':'John'

可以縮寫成這樣

1
2
3
4
5
6
7
8
function createObj( key, value){
const obj={
[key] = value
}
return obj
}
const person = createObj('name','Ken')
//'name':'John'

甚至可以做計算

1
2
3
4
5
6
7
8
function createObj( key, value){
const obj={
['last '+key] = value
}
return obj
}
const person = createObj('name','Ken')
//'last name':'John'