在JavaScript中关闭多个方括号 [英] Closure in Javascript with multiple brackets

查看:92
本文介绍了在JavaScript中关闭多个方括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以有任何一个解释如何这个函数警报,当更多没有括号的参数传递。我不能清楚地理解它。

Could any one explain how this function alert, when more no of brackets of parameters are passed. I could not able to understand it clearly.

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


推荐答案

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

The first time your function is called, the first value is stored in sum. After that function f(b) will be returned, maintaining the provisional result in sum. With each consecutive call you execute function f - you perform sum += b and return f again. If a string context is required (such as in the alert, or a console.log) f.toString is called instead, returning the result (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
}

说明:

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

这篇关于在JavaScript中关闭多个方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆