【ES6入门07】:函数扩展

本文深入探讨了JavaScript函数的多种特性,包括参数默认值、作用域、rest参数、箭头函数及函数尾调用等,提供了丰富的代码示例,帮助读者理解和掌握函数的高级用法。

函数扩展

函数参数的默认值

{
    function test(x, y = 'world') {
        console.log(x, y);
    }
    test('hello'); // hello world
    test('hello', 'can'); // hello can
}

参数的作用域

{
    let x = 'hi';
    function test2(x, y = x) {
        console.log(x, y);
    }
    function test3(a, y = x) {
        console.log(a, y);
    }
    test2('can'); // can can
    test3('can'); // can hi
}

rest的参数

{
    // ...arg将所有参数转换为数组 ...表示rest参数
    function test4(...arg) {
        for (let v of arg) {
            console.log(v);
        }
    }
    test4(1, 2, 3, 'a'); // 1  2  3  'a'

    // 扩展运算符
    console.log(...[1, 2, 4]); // 1 2 4
}

箭头函数

{
    let fn = arg => arg * 2; // 只有一个参数可以省略()
    let fn2 = () => 5; // 没有参数写()
    // 当返回值为对象时,用()包住返回值,不然会报错
    let fn3 = (name, age) => ({name, age});
    console.log(fn(3)); // 6
    console.log(fn2()); // 5
    console.log(fn3('can', 18)); // {name: "can", age: 18}
    // 注意,使用箭头函数时,注意this的指向
}

函数尾调用

{
    // 判别是否函数尾调用的方法:函数的最后一个语句是不是一个函数
    // 当函数嵌套过多,当一个函数依赖另一个函数时,可使用尾调用优化性能
    function test(x) {
        console.log(x);
    }
    function fn(x) {
        return test(x); // 尾调用,最后的语句是函数
    }
    fn(123); // 123
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值