函数的扩展

1 函数参数默认值

1.1 ES5默认参数

ES6 之前,不能直接为函数的参数指定默认值,只能采用变通的方法。

function fn1(a, b) {
    // b = b || "world";
    if (typeof b === "undefined") {
        b = "world";
    }
    console.log(a, b);
}
fn1("hello", "");
fn1("hello");
fn1("hello", "world");

1.2 ES6 默认参数

ES6 允许为函数的参数设置默认值,即直接写在参数定义的后面。

function fn2(a, b = "world") {
    console.log(a, b);
}
fn2("hello", "");
fn2("hello");

2 rest参数

  • ES6 引入 rest 参数(形式为...变量名),用于获取函数的多余参数,这样就不需要使用arguments对象了。rest 参数搭配的变量是一个数组,该变量将多余的参数放入数组中。

  • 和普通参数混合使用的时候,需要放在参数的最后

  • 函数的length属性,不包括 rest 参数

function fn3(...arg) {
    console.log(arg);
}
fn3(1, 2, 3, 4, 5)

//和普通参数混合使用的时候,需要放在参数的最后
function fn4(a, b, ...arg) {
    console.log(a, b, arg);
}
fn4(1, 2, 3, 4, 5)

3 箭头函数

3.1 什么是箭头函数

ES6 允许使用“箭头”(=>)定义函数

3.2 箭头函数的写法

箭头函数分为以下几种情况

  • 只有一个参数 并函数体是一句话的时候
  • 没有参数或者多个参数的时候,参数的括号不能省略
  • 当函数体不是一句话的时候
//1. 只有一个参数 并函数体是一句话的时候(如果是返回值则可以省略return)
// let f1 = function (n) {
//     return n + 1;
// }

let f1 = n => n + 1;
console.log(f1(2))

let arr = [1, 2, 3, "a", 5, 6, 7];
let result = arr.find(item => typeof item === "string");
console.log(result);


//2.没有参数或者多个参数的时候,参数的括号不能省略
let f2 = (a, b) => a + b;
console.log(f2(1, 2));

let f3 = () => console.log("hello");
f3();

//3.当函数体不是一句话的时候
let f4 = (a, b) => {
    console.log(a);
    console.log(b);
    console.log(a + b);
    return "ok~"
}
console.log(f4(1, 2))

3.3 箭头函数的注意事项

  • 关于this 箭头函数没有自己的this,箭头函数内部的this并不是调用时候指向的对象,而是定义时指向的对象

    document.onclick = function () {
           console.log(this)//普通函数的this指向调用对象
    }
    
    document.onclick = () => {
         //定义这个箭头函数的时候,是在window环境下定义的,所以指向window
         console.log(this);
    }
    
    document.onclick = function () {
          console.log(this);
          let f = () => {
              console.log(this);
          }
          f();
    }
    
    document.onclick = () => {
          console.log(this);
          let f = () => {
              console.log(this);
          }
          f();
    }
  • 箭头函数不能用于构造函数,也就是不能使用new关键字调用

    let F2 = () => { };
    new F2();//F2 is not a constructor
  • 箭头函数没有arguments对象

    let f3 = () => {
          console.log(arguments);//arguments is not defined
    }
    f3(1, 2, 3, 4, 5)
  • 箭头函数不能使用yield命令,意味着不能当作gennerator函数(后边会讲)

posted @   z_bky  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示