I have this two methods :
Cluster.prototype.initiate_xhr_request = function(url, callback) {
var self = this,
request = (Modernizr.test_xmlhttprequest) ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState === 4) {
switch(request.status) {
case 200:
callback.apply(request,[ request.statusText ]);
break;
case 400:
callback.apply(request,[ request.statusText ]);
break;
default:
break;
};
} else
console.log('An error occured during the XHR request');
}
};
request.open("HEAD", url, false);
request.send();
};
Cluster.prototype.operations = {
'&&': function(array){
return array.reduce(function(previousValue, currentValue, index, array){
return previousValue && currentValue;
})
},
'||' : function(array){
return array.reduce(function(previousValue, currentValue, index, array){
return this.initiate_xhr_request(previousValue) || currentValue;
})}
};
EDIT : The methods are invoked as it follows :
Cluster.prototype.calculate = function(operation, array){
return this.operations[operation](array);
};
/* call the calculate function */
this.calculate('&&', some_array);
Obviously, this line this.initiate_xhr_request(previousValue) won’t work. I kept trying to find a good solution of doing what I’m trying to do there, but I couldn’t find one (: Is there a way of doing that and keeping the structure I have the same ?
You can use
.callor.applyto manually set thethisvalue of the method you’re invoking.Here I set the
thisvalue ofthis.operations[operation]to that in the current lexical environment. (Using.applyinstead of.callwould do the same, but would take yourarrayand pass its members as individual args, which you don’t seem to want.)Now in those methods, the
thisvalue will be what you expect, except that you need to make sure thethisvalue is retained in then.reduce()callback for the"||"method.The classic way to do that is to keep a variable reference to the outer lexical environment, an reference that variable in the callback:
But a more modern way is to use
Function.prototype.bindto create a new function with thethisvalue manually bound: