函數擴展

函數新增特性

  • 參數默認值
  • rest參數
  • 擴展運算符
  • 箭頭函數
  • this綁定
  • 尾調用

    參數默認值

function test(x, y = 'world'){
    console.log('默認值',x,y)
}
test('hello')
//默認值 hello world
test('hello', 'me')
//默認值 hello me
let x = 'test';
function test2(x, y = x){
    console.log('作用域', x, y);
}
test2('me');
//作用域 me me
test2();
//作用域 undefined undefined 

rest參數

function test3(...args){
    for(let v of args){
        console.log('rest',v);
    }
}
test3(1,2,3,4,'a')
/**
* rest ⇒ 1
* rest ⇒ 2
* rest ⇒ 3
* rest ⇒ 4
* rest ⇒ a
*/

擴展運算符

console.log(...[1,2,4]);
//1 2 4
console.log('a',...[1,2,3]);
//a 1 2 3

箭頭函數

let arrow = v => v*2;
console.log('arrow', arrow(3));
//arrow ⇒ 6
let arrow = () => 5;
console.log(arrow());
//5

this綁定

let obj = {
    fn:function(){
        setTimeout(() => {
            console.log(this);
        });
    }
}
obj.fn();//object this指向函數的宿主對象

尾調用

function tail(x){
    console.log('tail',x);
}
function fx(x){
    return tail(x);
}
fx(123)
//tail ⇒ 123
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章