I am writing a .sort function that sorts an array of objects by one of their properties. See the snippet below.
PriorityQueue.prototype.sort = function () {
var criterium = this.criteria; // For some reason using this.criteria in the next line doesn't work.
this.queue.sort(function(a,b) {
return b[criterium] - a[criterium]
});
}
This works, but I'm curious why I have to define the variable criterium. If I were to use this.criteria within the sort function (i.e. "return b[this.criteria] - a[this.criteria]) then they return 'undefined'. For example, see the below code
PriorityQueue.prototype.sort = function () {
var criterium = this.criteria;
this.queue.sort(function(a,b) {
return console.log(a[criterium] + '___' + a[this.criteria]) // 10___undefined
});
}
Here, a[criterium] correctly returns its associated number (10) whereas a[this.criteria] returns undefined. This happens despite that criterium = this.criteria.
Does anyone know why I can't use this.criteria within the sort function?