參數默認值
在ES6中,函數的參數可以設置默認值。
實參爲null
,形參爲null
。
實參沒有參數
或者爲undefined
,形參爲默認值。
(function(a, b = 10, c = 3, d = 4, e = 5) {
console.log(a, b, c, d, e)
})(1, 2, undefined, null)
// a => 1
// b => 2
// c => 3
// d => null
// e => 5
函數參數默認值存在暫時性死區,未初始化賦值的參數值無法作爲其他參數的默認值。
function f(x, y = x) {
console.log(x, y);
}
f(1);
// x => 1
// y => 1
function f(x = y, y) {
console.log(x, y);
}
f(undefined, 1);
// Error: Cannot access 'y' before initialization (暫時性死區)
箭頭函數
箭頭函數是一種更加簡潔的函數書寫方式。
原始寫法
const fun = function(num) {
return num;
}
箭頭函數
const fun = (num) => {
return num;
}
fun(3)
// 3
如果參數只有一個,可以省略 ( )
const fun = num => {
return num;
}
fun(3)
// 3
如果箭頭函數只有一條返回語句,可以省略 { }
和 return
const fun = num => num
fun(3)
// 3
如果返回值是一個對象時,省略後就會認爲成函數體,此時會語法報錯,我們只需要將返回的對象用( )
包裹起來
// 省略前
const obj = (a, b) => {
return {
a: a,
b: b
}
}
// 省略後 SyntaxError
const obj = (a, b) => {
a: a,
b: b
}
// 把返回值用
const obj = (a, b) => ({
a: a,
b: b
})
箭頭函數沒有this
,argument
,new.target
在箭頭函數中,this
,argument
,new.target
分別對應的是箭頭函數外層的this
,argument
,new.target
。
const fun = () => {
console.log(this)
}
fun()
// Window
const obj = {
fun: function() {
const func = () => {
console.log(this);
}
func(4, 5, 6)
}
};
obj.fun(1, 2, 3)
// fun
箭頭函數沒有原型
箭頭函數沒有原型,佔用空間非常小,不能當成構造函數來使用。
const fun = () => true
console.log(fun.prototype)
// undefined