I have a code which adds up a range of values. It takes two or three arguments and then create an array using those values and then add them up. My reduce object has a addup
method which reduce its this.arr
property using array.reduce()
method. I have found that the THIS key indicates the global object inside reduce function. Why it indicates to global object inside reduce? How can I stick to the current object inside reduce using closure or something like that? I tried but couldn't find a way to figure this out.
There is nothing wrong with the code.It works fine.
addup method of reduce object:
addup:function(){
this.sum= this.arr.reduce(function(previous,current,index,array){
console.log(this);
return previous+current;
});
},
full code if required:
<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>