Skip to main content

箭头函数

  • 语法:

    let arrowfuntion=()=>{
    return 1;
    }

    =>:使用胖箭头,定义函数表达式。

    PS:

    • 箭头后只有一行代码,可以不使用大括号

      let arrowfuntion=()=> 1;
      let arrowfuntion=()=> return 1; //无效
    • 没有参数或多个参数,需要括号

      let arrowfuntion=()=>1;
      let arrowfuntion=(x,y)=>x+y;
    • 一个参数,可不需要括号

      let arrowfuntion=x=>x;
      let arrowfuntion= x,y=>x+y //无效,多个参数必须用括号
  • 使用场景:

    • 适合

      1. 任何可以使用函数表达式的地方,都可以使用箭头函数。

      2. 适合嵌入函数的场景

        let ints=[1,2,3];
        console.log(ints.map((i)=>{return i+1 })) //[2,3,4]
    • 不适合

      1. 需要使用arguments、super、new.target的场景
      2. 用做构造函数的场景

Q:箭头函数能否获取prototype属性?

  • A:不能

    function giveLydiaPizza() {
    return "Here is pizza!"
    }

    const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already."

    console.log(giveLydiaPizza.prototype)//获取其构造函数
    console.log(giveLydiaChocolate.prototype)//undefined