I am having problems wrapping my brain around a scoping issue using a prototype function in an array while sorting it. I can make it work on a static item, but when I attempt to generalize to work on the array I start seeing "is not a function" errors. Here is my current rendition of the code. Any help would be appreciated.
function Automobile(year, make, model, type) {
this.year = year; //integer (ex. 2001, 1995)
this.make = make; //string (ex. Honda, Ford)
this.model = model; //string (ex. Accord, Focus)
this.type = type; //string (ex. Pickup, SUV)
}
Automobile.prototype.logMe = function(bool) {
console.log("Working"); //testing function
if (bool == true) {
console.log(this);
}
};
/*Sample Array*/
var automobiles = [
new Automobile(1995, "Honda", "Accord", "Sedan"),
new Automobile(1990, "Ford", "F-150", "Pickup"),
new Automobile(2000, "GMC", "Tahoe", "SUV"),
new Automobile(2010, "Toyota", "Tacoma", "Pickup"),
new Automobile(2005, "Lotus", "Elise", "Roadster"),
new Automobile(2008, "Subaru", "Outback", "Wagon")
];
/*This function sorts arrays using an arbitrary comparator.*/
function sortArr(comparator, array) {
array.sort(function(a, b) {
return comparator(a, b);
});
return array;
}
function exComparator(int1, int2) {
if (int1 > int2) {
return true;
} else {
return false;
}
}
function yearComparator(auto1, auto2) {
return exComparator(auto1.year, auto2.year);
}
/* Output*/
console.log("*****");
console.log("The cars sorted by year are:");
forEach(sortArr(yearComparator, automobiles), automobiles.logMe(true)); //This is not right!
function forEach(array, doStuff) {
for (var i = 0; i < array.length; i++)
doStuff(array[i]);
}
trueorfalse. Instead, they're supposed to return a negative number, zero, or a positive number, to indicate that the first value should go before the other, if they're the same, or that the second value should go before the first.sortArrfunction is functionally identical toarray.sort(comparator)forEach.