代码之家  ›  专栏  ›  技术社区  ›  Munerz

闭包和箭头语法[重复]

  •  0
  • Munerz  · 技术社区  · 6 年前

    所以在我看来现在显然是错误的是,

    return arg => arg*2
    

    return (arg)=>{arg*2}
    

    我一直认为箭头函数在语法上更简洁。

    但是用这样的闭包来做是行不通的。

    function addTwoDigits(firstDigit){
        return (secondDigit)=>{firstDigit + secondDigit}
    }
    let closure = addTwoDigits(5);
    console.log(closure(5)) // Undefined
    

    function addTwoDigitsV2(firstDigit){
        return secondDigit => firstDigit + secondDigit
    }
    let closure2 = addTwoDigitsV2(10);
    console.log(closure2(10))// 20
    
    4 回复  |  直到 6 年前
        1
  •  3
  •   Atul    6 年前

    箭头函数在这里的工作方式不同:-

    (x)=> x*2 ; // dont have to return anything, x*2 will be returned
    is not same as 
    (x) =>{x*2}
    //here you need to return something otherwise undefined will be returned
    
        2
  •  2
  •   mariamelior    6 年前

    使用{}时,必须设置return

    return (arg)=>{return arg*2}
    
        3
  •  2
  •   Barmar    6 年前

    return 如果箭头后有表达式,则自动执行。如果箭头后面跟着一个大括号,则它被视为函数体周围的大括号,因此必须编写 返回

    arg => arg * 2
    

    相当于:

    (arg) => { return arg * 2; }
    

    function addTwoDigits(firstDigit) {
      return (secondDigit) => {
        return firstDigit + secondDigit
      }
    }
    let closure = addTwoDigits(5);
    console.log(closure(5))
        4
  •  1
  •   Scott Sauyet    6 年前

    你需要一个 return 如果arrow函数的主体被包装在 { ... } .

    { } 返回 { - } ,你需要 陈述。

    括号在这里不是问题。如果有多个参数,则需要它们。有了一个,它们是可选的。