将此设置为array.prototype.reduce()中的当前对象

时间:2014-09-10 00:40:39

标签: javascript arrays

我有一个代码,它会添加一系列值。它需要两个或三个参数,然后使用这些值创建一个数组,然后将它们相加。我的reduce对象有一个addup方法,可以使用this.arr方法减少其array.reduce()属性。我发现THIS键表示reduce函数里面的全局对象。为什么它表示内部的全局对象减少?我如何坚持使用闭包或类似的内部减少当前对象?我试过但找不到解决这个问题的方法。

代码没有问题。工作正常。

减少对象的addup方法:

addup:function(){

       this.sum= this.arr.reduce(function(previous,current,index,array){
            console.log(this);
            return previous+current;  

        });

    },
如果需要,

完整代码:

<html>
<body>
<script>
    var reduce={
        start:null,
        end:null,
        step:null,
        args:null,
        arr:[],
        sum:null,
        getrange:function(){
            if(arguments.length==2){
                this.args=arguments.length;
                this.start=arguments[0];
                this.end=arguments[1];
             }
            else if(arguments.length==3){
                this.args=arguments.length;
                this.start=arguments[0];
                this.end=arguments[1];
                this.step=arguments[3];

             }
        },
        setarr:function(){
            if(this.args==2){
                for(i=this.start;i<=this.end;i++){
                    this.arr.push(i);   

                }   

            }
            else if(this.args==3){
                for(i=this.start;i<=this.end;i+=this.step){
                    this.arr.push(i);   

                }   

            }

        },
        addup:function(){

           this.sum= this.arr.reduce(function(previous,current,index,array){
                console.log(this);
                return previous+current;  

            });

        },

        show:function(){
            console.log(this.sum);

        },
        cleanup:function(){
            this.arr.splice(0,this.arr.length);
            this.sum=null;

        }

    }
    reduce.getrange(1,5);
    reduce.setarr();
    reduce.addup();
    reduce.show();
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

您可以使用bind更改功能的上下文。

Live Demo

function callback(previous,current,index,array){
    console.log(this);
    return previous+current;  
}

[1,2,3,4,5].reduce(callback);

var myObject = {}; 
[1,2,3,4,5].reduce(callback.bind(myObject));

答案 1 :(得分:1)

在执行this之前,只需存储对this.arr.reduce()的引用,以便您可以在回调中使用它:

addup:function() {
    var self = this;

    this.sum= this.arr.reduce(function(previous,current,index,array){
        console.log(self);
        return previous + current;  
    });
},