用多个括号关闭Javascript

PCA*_*PCA 17 javascript closures

当没有传递任何参数括号时,任何人都可以解释这个函数如何发出警报.我无法清楚地理解它.

function sum(a) {

  var sum = a

  function f(b) {
    sum += b
    return f
  }

  f.toString = function() { return sum }

  return f
}

alert( sum(1)(2) )  // 3
alert( sum(5)(-1)(2) )  // 6
alert( sum(6)(-1)(-2)(-3) )  // 0
alert( sum(0)(1)(2)(3)(4)(5) )  // 15
Run Code Online (Sandbox Code Playgroud)

Chr*_*oph 18

第一次调用函数时,第一个值存储在sum.之后function f(b)将返回,保持临时结果sum.每次连续调用都会执行函数f- 执行sum += b并再次返回f.如果需要字符串上下文(例如,在alerta或a中console.log)f.toString,则返回结果(sum).

function sum(a) {

  var sum = a

  function f(b) {
    sum += b
    return f  //<- from second call, f is returned each time
              //   so you can chain those calls indefinitely
              //   function sum basically got "overridden" by f
  }

  f.toString = function() { return sum }

  return f //<- after first call, f is returned
}
Run Code Online (Sandbox Code Playgroud)

说明:

alert( sum(6)(-1)(-2)(-3) )  // 0
           /\ function sum called, f returned
              /\ the returned function f is called, f returns itself
                  /\ again
                     /\ and again
                         /\ at last, alert() requires string context,
                            so f.toString is getting invoked now instead of f
Run Code Online (Sandbox Code Playgroud)