//function add(x) {________}; alert(add(2)(3)(4));

  题目为补全function add, 使add(2)(3)(4) 结果为9. 原文地址 http://www.cnblogs.com/rubylouvre/archive/2012/02/15/2351991.html 

看到题目第一时间会进行加法运算 2+3+4 = 9, 所以绝大多数都会想办法实现加法运算,同时 我们可以看到进行了三次方法调用,所以必须保证每次调用的返回值是function类型,

而且,为了保存加法运算的结果,还要利用闭包特性,定义个自由变量来保存,于是下面的代码产生了

function add(x){
  var res = 0;
  return (function(t){
    res += t;
  })(x)
}

  run的结果: undefined is not a function

Oh 此时我们只是把运算结果的值保存起来了,没有return

于是乎修改:

function add(x){
  var res = 0;
  return (function innerAdd(t){
    res += t;
    return res;
  })(x)
}

  run的结果,number is not a function

很明显,2(3)(4),会抛错。因为每次return的值不是function,于是,可以想到每次可以返回该innerAdd,同时重写该function的toString()方法,

于是:

function add(x){
  var res=0;
  return (function innerAdd(x){
    res = x+res;
    arguments.callee.toString = function(){
      return res;
    };
    return arguments.callee;
  })(x);
}

其他方式:

特定的方式,利用function的 [[scope]]属性,这种方式局限性太大,代码需要根据调用次数的多少来变化

function add(x){
  return function(y){
    return function(z){
      return x+y+z;
    }
  }
}

 

 引用文章作者的方法:

function add(x){
  if(add.i){
    add.i += x;
  }else{
    add.i=x;
  }
  add.toString = function(){
    return add.i;
  }
  return add;
}

 地址 : http://jsbin.com/mamajefu/1/edit

posted on 2014-08-11 15:47  Earlene  阅读(142)  评论(0编辑  收藏  举报