函數擴展
函數新增特性
- 參數默認值
- rest參數
- 擴展運算符
- 箭頭函數
- this綁定
- 尾調用
{
//函數參數默認值
//默認值後面,不能有,沒有默認值的變量
//function(x,y=123,z) 這是錯誤的
//function(x,y=123,z=444) 這是可以的
function foo(x, y = 'y的默認值'){
console.log("默認值",x,y)
}
foo(123)//只傳一個參數,y就用默認值
//123 y的默認值
foo(12,33)//12,33
}
{
//函數作用域問題
let x = 100
function fn1(x,y=x){
console.log(x,y)
}
fn1('hello')// hello hello
//hello對應的是形參x ;y=x,那麼y就是取得前面那個x
//因爲x在函數作用域中已經定義過了,所以y=x中的x就是函數內定義的x
fn1()//undefined undefined
function fn2(c,y=x){
console.log(c,y)
}
//因爲函數中沒有定義過x,那麼y=x中的x就是let x = 100
fn2(200)//200 100
}
{
//rest參數,rest參數之後不能有別的參數了,因爲它在轉換參數的時候不知道什麼時候截止
//就是把你的參數轉成了數組
//也就是在你不確定參數的時候,把傳入的參數轉換成了數組
function test3(...arg){
for(let v of arg){
console.log('rest',v)
}
}
test3(1,2,3,4,'a')
//1
//2
//3
//4
//'a'
function test4(x,...arg){
for(let v of arg){
console.log('rest',v,x)
}
}
test4(1,2,3,4,'a')
//2,1
//3,1
//4,1
//‘a’,1
}
{
//擴展運算符
//可以理解爲擴展運算符是rest參數的逆運用
console.log(...[1,2,4])//1,2,4 //把數組拆成了離散值
//rest參數是把參數轉成數組
console.log('a',...[1,2,4])//a,1,2,4
}
{
//箭頭函數
let arrow = v => v*2;//定義arrow是函數
let arrow1 = () => 10;//沒有參數的箭頭函數
//函數名
//前面是參數 (v是參數)
//後面是返回值
console.log(arrow(3))//6
console.log(arrow1())//10
}
{
//尾調用,出現在函數編程裏,也就是說,函數的最後一句話,是不是一個函數
//尾調用提升性能
function tail(x){
console.log(x)
}
function fx(x){
return tail(x);
}
fx(123)//123
//這就是尾調用
}
做箭頭函數的時候一定要注意this綁定
尾調用的好處有哪些?
遞歸是函數嵌套相當耗費資源,可以用尾調用做優化