ES6--函数扩展

函数新增特性

函数默认值,rest参数,扩展运算符,箭头函数,this绑定,尾调用

函数参数的默认值

{
    //函数参数默认值
    function test(x,y='你好'){
        console.log(x,y)
    }
    test("wode")
    //wode 你好
    test("wode",'tahao')
    //wode tahao
    //默认值后面不能再有 没有默认值的变量,比如参数c但是没有默认值
}
{
    let x='test';
    function test2(x,y=x){
        console.log(x,y)
    }
    test2("hi")
    //hi hi
    //参数中的值取到的实参,实参拥有大的权限
}

rest参数

在不确定有几个参数的时候,可以用...arg,将参数转化成数组,rest参数之后不能有其他的参数。

{
    //rest参数
    function test3(...arg){
        for(let v of arg){
            console.log(v)
        }
    }
    test3(1,2,3,4,5,'a')
    //1,2,3,4,5,a
}

箭头函数

{
    //arrow是函数名,v是参数,v*2是返回值
    let arrow = v => v*2;
    console.log(arrow(3))
    //6
    let arrow2=()=>5;
    console.log(arrow2());
    //5
}

关于箭头函数this的指向,箭头函数中this指向最外层函数的this,是词法作用域,由上下文确定,所以以前的那种var that = this可以不再使用。

尾调用

尾调用的概念非常简单,一句话就能说清楚,就是指某个函数的最后一步是调用另一个函数。可以提高性能。

{
    function tail(x){
        console.log(x)
    }
    function fx(x) {
        return tail(x)//尾调用
    }
    fx(123)
    //123
}

你可能感兴趣的:(ES6--函数扩展)