【ES6入门07】:函数扩展

发布时间:2019-08-09 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了【ES6入门07】:函数扩展脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

函数扩展

函数参数的默认值

{
    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
}

脚本宝典总结

以上是脚本宝典为你收集整理的【ES6入门07】:函数扩展全部内容,希望文章能够帮你解决【ES6入门07】:函数扩展所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。