Javascript组合原型函数

时间:2013-10-12 15:56:56

标签: javascript prototype

Function.prototype.times = function(val){
        var that = this;
        return function (arg) {
            if(val == 0){
                return that.call(this,arg);
            }
            else{
                var newArg = that.call(this,arg);
                var newVal = val - 1;
                return that.call(that.times,newVal,newArg);
            }
        }
    }
    var add_two = function (num) { return num + 2; };
    var add_six = add_two.times(3);
    alert(add_six(2));

有人可以帮我解释为什么这段代码不起作用?谢谢!

2 个答案:

答案 0 :(得分:0)

请检查一下。 Link

基本上,add_six不是函数,而是函数的引用。  检查下面的代码

 alert(typeof add_six(2));

答案 1 :(得分:0)

这有几个问题,这是一个固定的版本:

Function.prototype.times = function(val){
    var that = this;
    return function (arg) {
        if(val == 1) {
            return that.call(this,arg);
        } else{
            var newArg = that.call(this,arg);
            var newVal = val - 1;
            return that.times.call(that,newVal)(newArg);
        }
    }
}
var add_two = function (num) { return num + 2; };
var add_six = add_two.times(3);
alert(add_six(2)); // 8